C++ VisualStudio2008中的嵌套继承问题
我目前正在开发一个基于小部件的图形用户界面。它的结构是一棵树,小部件是树的叶子,容器是树的节点。这个结构的(可解决的)问题是小部件类引用了作为其父容器的容器。但是,这使得容器类无法访问小部件类的受保护成员(这里的“draw”成员造成了麻烦) 下面是导致问题的代码的核心。当然,这可以通过公开成员来解决。然而,这不是我想要的风格 ClassesTest.h:C++ VisualStudio2008中的嵌套继承问题,c++,visual-c++-2008,C++,Visual C++ 2008,我目前正在开发一个基于小部件的图形用户界面。它的结构是一棵树,小部件是树的叶子,容器是树的节点。这个结构的(可解决的)问题是小部件类引用了作为其父容器的容器。但是,这使得容器类无法访问小部件类的受保护成员(这里的“draw”成员造成了麻烦) 下面是导致问题的代码的核心。当然,这可以通过公开成员来解决。然而,这不是我想要的风格 ClassesTest.h: class Container; class Widget { public: Widget(Container *parent);
class Container;
class Widget {
public:
Widget(Container *parent);
virtual ~Widget();
protected:
Container *parent;
virtual void draw();
};
class Container : public Widget {
public:
Container(Container *parent);
virtual ~Container();
protected:
std::list<Widget *> childs;
private:
friend Widget::Widget(Container *);
friend Widget::~Widget();
virtual void draw();
void addChild(Widget *child);
void removeChild(Widget *child);
};
如有任何建议,将不胜感激
Filip就您的具体问题而言,您的代码与此基本相同:
class Base
{
protected:
virtual void f() {}
};
class Derived : public Base
{
void h()
{
Base().f(); // no can do - Base() creates another instance.
f(); // sure, why not. it's the same instance, go ahead.
Derived().f(); // sure, why not. it's the same type, go ahead.
}
};
问题在于,尽管派生的
继承自基
,但它仍然无法访问基
的受保护成员。访问权限的工作方式如下:
派生的
可以不访问Base
的受保护内容,如果Base
是不同的实例Derived
可以在自己的实例中访问Base
的受保护内容Derived
可以访问另一个Derived
的私人资料解决问题的最快方法可能是使
Container::draw()
成为Widget
的朋友,就您的具体问题而言,您的代码与此基本相同:
class Base
{
protected:
virtual void f() {}
};
class Derived : public Base
{
void h()
{
Base().f(); // no can do - Base() creates another instance.
f(); // sure, why not. it's the same instance, go ahead.
Derived().f(); // sure, why not. it's the same type, go ahead.
}
};
问题在于,尽管派生的
继承自基
,但它仍然无法访问基
的受保护成员。访问权限的工作方式如下:
派生的
可以不访问Base
的受保护内容,如果Base
是不同的实例Derived
可以在自己的实例中访问Base
的受保护内容Derived
可以访问另一个Derived
的私人资料Container::draw()
成为Widget
的朋友
class Base
{
protected:
virtual void f() {}
};
class Derived : public Base
{
void h()
{
Base().f(); // no can do - Base() creates another instance.
f(); // sure, why not. it's the same instance, go ahead.
Derived().f(); // sure, why not. it's the same type, go ahead.
}
};