【发布时间】:2010-09-30 20:13:49
【问题描述】:
#include <iostream>
using namespace std;
class Base
{
public:
Base(){cout <<"Base"<<endl;}
virtual ~Base(){cout<<"~Base"<<endl;}
virtual void foo(){ cout<<"foo base"<<endl;}
};
class Derived: private Base
{
public:
Derived(){cout<<"Derived"<<endl;}
virtual ~Derived(){cout<<"~Derived"<<endl;}
virtual void foo(){ cout<<"foo dervied"<<endl;}
};
int main(int argc, char *argv[])
{
Base *pb = new Derived;
Derived d;
d.foo();
return 0;
}
当我执行上述示例程序时,我收到以下错误: protected.cpp:在函数“int main(int, char**)”中: protected.cpp:26: error: ‘Base’ is an inaccessible base of ‘Derived’
为什么不能用基指针创建派生对象????
所以我可以创建一个 Derived 类的实例,例如
Derived d
Derived d1= new Derived;
但是像这样从基类指针创建实例
Base * b = new derived
会失败。
这是因为 Derived 实际上不是从 Base 派生的派生类,当派生 procted 和 private 时??
这样说对吗??????
【问题讨论】:
-
为什么这个问题得到 3 票反对?这是一个完全合理的问题。 +1,荒谬。
标签: c++ inheritance