c++ - 实例化从 Base 私有(private)或 protected 继承的派生类

标签 c++ inheritance

我有以下假设代码:

class Base {
public:
    virtual void print() {
        std::cout << "Base\n";
    }
    // assume virtual destructor
};

class Derived : private Base {
public:
    void print() {
        std::cout << "Derived\n";
    }
};

int main() {
    // Derived d{};   works fine
    Base *pd = new Derived{}; // doesn't work
    pd->print();
    // assume memory is deallocated  
}

起初,我认为它会起作用,因为构造函数无论如何都不会被继承。但编译器给出错误:

error: 'Base' is an inaccessible base of 'Derived'

我无法弄清楚到底发生了什么?

最佳答案

这是一个很好的猜测,但问题不在于构造函数或成员函数。

在行

Base *pd = new Derived{}; // doesn't work

编译器隐式地将右侧 new Derived{}(其类型为 Derived*)转换为 Base* 类型.

该标准用来描述何时可以将指向派生类的指针隐式转换为指向基类的指针的术语是可访问性。从第 11.2/5 小节开始:

If a base class is accessible, one can implicitly convert a pointer to a derived class to a pointer to that base class

列出了一些可以使基类可访问的技术条件(如果您真的关心的话,请为 11.2/4),但 Base 不满足这些条件。

简而言之,private 继承隐藏了基类,并且访问说明符 private 需要为 public 才能编译代码。希望有帮助。

关于c++ - 实例化从 Base 私有(private)或 protected 继承的派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32002553/

相关文章:

c# - 你能强制在类构造函数中调用一个方法,否则会抛出编译错误吗?

c++ - 接口(interface)实现与私有(private)继承的交互

c++ - 将对象分配到 unordered_map 数组?

c++ - 是否可以将整个枚举集作为参数传递?

eclipse - Eclipse 支持的用于删除父类(super class)依赖性的重构可能是什么?

python - 如何有效地传递参数(python 中的**kwargs)

java - 返回泛型类型的新实例,其中 T 设置为给定 arg 的类型

c++ - 归并排序函数(自然归并排序)

python - 使用pybind11和pytorch在C++中运行python时出现无效的指针错误

c++ - 在 C++ FAT 文件系统仿真中使用继承委派构造函数