【发布时间】:2016-03-11 18:56:03
【问题描述】:
伙计们,我在技术博客上遇到了这个问题,问题是解决以下代码中生成的编译器错误的正确解决方案是什么。我已经搜索了几个小时,但无法得到答案。
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 中所说的,但有一些困难。 (我希望有人也可以实现A中的想法),下面是我的代码:
class derived:public SomeClass{};
void use_someclass()
{
derived::Nest *nst=SomeClass::createNest();
nst->nested = 5;
}
在上面,我们的想法是我们可以从派生类访问 Nest 定义。 在函数use_someclass()中,第一行右边是静态函数,返回Nest*类型,但是左边不知道怎么匹配右边的类型。 “派生::巢”是错误的。编译器错误:无法访问受保护的成员。 Nest 只是 SomeClass 中的一个定义,不是成员。
我们可以用什么来替换“derived::Nest”?派生当然看到了Nest的定义,但我不知道如何“说”它。也许以某种方式通过“this”指针。
【问题讨论】:
-
您可以在派生类中声明 use_someclass 以使用 Nest。
标签: c++ inheritance polymorphism protected