无法在派生 class 的构造函数的初始化中访问受保护的函数

Impossible to access protected function in the initialization of the derived class's constructor

我正在尝试实现一个直接继承自 class Shape 的 class UnionUnion 是由多个形状组成的形状).

Shape 的(受保护的)构造函数将 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;

}

with get_center() class Shape.

的受保护虚函数
class Shape
{
protected:
     Shape (const Point& center) : center(center) {};
     virtual const Point& get_center() const =0;
     ...
private:
     const Point center;
}

但是,当我在 Union 构造函数的初始化列表中调用 get_center() 时,出现错误提示 "get_center() is a protected member of Shape".

有人能解释一下为什么我不能从 subclass Union 调用 get_center() (它应该继承了这个功能)吗?

谢谢!

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

问题可以简化为

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

您只能通过派生的 class.

访问受保护的成员