伙计们,我在科技博客上遇到过这个问题,问题是什么问题才能解决在下面的代码中产生的编译器错误。我搜索了几个小时,无法得到答案。访问基类从派生类中受保护的嵌套类
class SomeClass
{
public:
int data;
protected:
class Nest
{
public:
int nested;
};
public:
static Nest* createNest(){return new Nest;}
};
void use_someclass()
{
SomeClass::Nest* nst = SomeClass::createNest();
nst->nested = 5;
}
A. Make function void use_someclass() a friend of class SomeClass.
B. Make the function createNest() a non-static function of SomeClass.
C. Declare the class Nest in public scope of class SomeClass.
D. Make the object nst a reference object, and make the function
createNest() return a Nest&.
E. Derive a class from SomeClass. Make the object nst a derived class
pointer so that it can access SomeClass's protected declarations.
C肯定是正确和琐碎的。 我相信A也是对的,特别是E是做这种事情的经典方式。 我想实现E中所说的,但有一些困难。 (我希望有人也可以实现在一个想法),下面是我的代码:
class derived:public SomeClass{};
void use_someclass()
{
derived::Nest *nst=SomeClass::createNest();
nst->nested = 5;
}
在上面
,这个想法是我们可以从一个派生类访问鸟巢定义。 在函数use_someclass()中,在第一行中,右侧是一个静态函数,并返回类型Nest *,但在左侧,我不知道如何匹配右侧类型。 “derived :: Nest”是错误的。编译器错误:无法访问受保护的成员。 Nest只是SomeClass中的一个定义,不是成员。
我们可以用什么来取代“derived :: Nest”?派生的确看到了Nest的定义,但我不知道如何“说”它。也许以某种方式通过“this”指针。
您可以在派生使用巢类中声明use_someclass。 –