c++ - protected 派生类

标签 c++ inheritance

 #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/

相关文章:

c++ - 有没有办法反省数组的大小?

c++ - 有没有办法检测函数是否被覆盖?

php - 如何从继承方法中调用 PHP 父方法?

javascript - AngularJS:函数内的变量 $scope 在函数外似乎未定义

c# - 错误: Does not contain a constructor that takes 0 arguments

c++ - 在 C++ 中对 STL 列表使用 push_back() 会导致访问冲突、崩溃

C++ 在不使用类的情况下验证日期

c++ - 从 const string 到 bool 的隐式转换

c++ - 标记字符串

javascript - 类型继承: Why do you have to create a new object instead of setting the prototype directly?