#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: 错误:‘Base’是‘Derived’不可访问的基础
为什么不能用基指针创建派生对象????
所以我可以创建一个派生类的实例,例如
Derived d
Derived d1= new Derived;
但是像这样从基类指针创建实例
Base * b = new derived
会失败。
这是因为 Derived 在派生过程和私有(private)时实际上不是 Base 的派生类??
这是正确的吗?????
最佳答案
Why its not possible to create Derived object with base pointer????
因为基数是私有(private)的
。这明确禁止将您的类视为来自外部的 Base
实例。从外部看,您的类 Derived
不是 Base
的子类,只是从类本身内部看。
protected
继承也是如此,唯一的区别是基类现在不再对自己的类私有(private),而是对任何派生类也是私有(private)的。但在外部,它的行为就像私有(private)继承。
关于c++ - protected 派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/433965/