朋友类:继承类不是朋友吗? [英] friend class : inherited classes are not friend as well?
问题描述
在C ++中,我有一个类A,它是类B的朋友。
我看起来继承类B不是类A的朋友。 p>
这是C ++的限制还是我的错误?
这里是一个例子。编译时,我在return new Memento行上遇到错误:
Memento :: Memento:无法访问在Memento中声明的私有成员。
class Originator;
class Memento
{
friend class Originator;
Memento(){};
int m_Data;
public:
〜Memento(){};
};
class Originator
{
public:
virtual Memento * createMemento()= 0;
};
class FooOriginator:public Originator
{
public:
Memento * createMemento()
{
return new Memento; //不可能访问Memento的私人成员
}
};
void main()
{
FooOriginator MyOriginator;
MyOriginator.createMemento();
}
我当然可以添加FooOriginator作为Memento的朋友,但那么,这意味着我必须将所有Originator继承的类作为Memento的朋友,这是我想避免的。
任何想法? >
查看: C ++的朋友范围
投票的精确副本。
我看起来像继承类的B不是类A的朋友。
正确
$ b b
我这是C ++的限制还是我的错误?
这是C ++的工作原理。我不认为这是一个限制。
In C++, I have a class A which is friend with a class B.
I looks like inherited classes of B are not friend of class A.
I this a limitation of C++ or my mistake ?
Here is an example. When compiling, I get an error on line "return new Memento":
Memento::Memento : impossible to access private member declared in Memento.
class Originator;
class Memento
{
friend class Originator;
Memento() {};
int m_Data;
public:
~Memento() {};
};
class Originator
{
public:
virtual Memento* createMemento() = 0;
};
class FooOriginator : public Originator
{
public:
Memento* createMemento()
{
return new Memento; // Impossible to access private member of Memento
}
};
void main()
{
FooOriginator MyOriginator;
MyOriginator.createMemento();
}
I could of course add FooOriginator as friend of Memento, but then, this means I would have to add all Originator-inherited classes as friend of Memento, which is something I'd like to avoid.
Any idea ?
See: Friend scope in C++
Voted exact duplicate.
I looks like inherited classes of B are not friend of class A.
Correct
I this a limitation of C++ or my mistake ?
It is the way C++ works. I don't see it as a limitation.
这篇关于朋友类:继承类不是朋友吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!