c++ - 无法在派生类的构造函数的初始化中访问 protected 函数

标签 c++ inheritance constructor initialization protected

<分区>

我正在尝试实现一个类 Union直接继承自类 Shape (Union 是由多个形状组成的形状)。

Shape 的( protected )构造函数需要 Point作为输入(代表形状的中心)。构建一个 Union对象,唯一的输入是形状列表(const vector<const Shape>)。实现 Union 的构造函数,我想使用初始化列表,如下所述

class Union : Shape
{
public:
     Union(const std::vector<const Shape> shapes): 
     Shape(shapes[0].get_center()), shapes(shapes) {};
     ...
private:
     const std::vector<const Shape> shapes;

}

get_center()Shape 的 protected 虚函数.

class Shape
{
protected:
     Shape (const Point& center) : center(center) {};
     virtual const Point& get_center() const =0;
     ...
private:
     const Point center;
}

但是,当我调用 get_center()Union 的初始化列表中构造函数,有一个错误说“get_center() 是 Shape 的 protected 成员”。

谁能解释一下为什么我不能调用 get_center()来自子类 Union (应该是哪个继承了功能)?

谢谢!

P.S.: 如果我设置函数 get_center()公开,就没有错误了。

最佳答案

问题可以简化为

struct Base
{
protected:
    int i = 0;
};

struct Derived : Base
{
    static void foo(Base& b)
    {
        b.i = 42; // Error
    }

    static void bar(Derived& d)
    {
        d.i = 42; // Ok
    }
};

Demo

您只能通过派生类访问 protected 成员。

关于c++ - 无法在派生类的构造函数的初始化中访问 protected 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57630443/

相关文章:

javascript - ES6 类中的构造函数和原型(prototype)中的构造函数之间的区别?

list - 带有委托(delegate)构造函数的构造函数初始化列表执行顺序

c++ - 为什么 C++17 destroy()/destroy_n() 函数向前运行(而不是向后运行)?

c++ - 唯一指针类内初始化

c++ - 为什么在删除派生类对象时调用基类析构函数(虚拟)?

c# - 我可以使用显式运算符来创建派生类吗?

ios - 类的多重继承

c++ - QGraphicsItem 鼠标中键按下事件

c++ - Qt 中的小部件 : Change background-color onclick

c++ - 类 Bar { 运算符 Foo(); }