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

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

本文关键字:访问 受保护 函数 初始化 派生 构造函数      更新时间:2023-10-16

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

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;
}

具有get_center()Shape的受保护虚函数。

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的受保护成员"。

有人可以解释为什么我不能从子类Union调用get_center()(它应该继承了函数(?

谢谢!

PS:如果我将功能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
}
};

演示

只能通过派生类访问受保护的成员。