【问题标题】:Impossible to access protected function in the initialization of the derived class's constructor [duplicate]在派生类的构造函数的初始化中无法访问受保护的函数[重复]
【发布时间】:2019-12-29 00:34:27
【问题描述】:

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

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

但是,当我在Union 构造函数的初始化列表中调用get_center() 时,出现错误说“get_center() 是Shape 的受保护成员”。

谁能解释我为什么不能从子类Union(应该继承该函数)调用get_center()

谢谢!

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

【问题讨论】:

  • 你真的要使用私有继承吗?
  • @NeilButterworth 是的。不管怎样,当我写class Union: public Shape {...}时,问题仍然存在。
  • @Jarod42 但UnionShape 的派生类。我不应该访问get_center()函数吗?
  • 来自Union,是的,不是来自Shape
  • This 可能会有所帮助

标签: c++ inheritance constructor initialization protected


【解决方案1】:

问题可以归结为那个

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-07
    • 2012-06-05
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 2020-02-20
    相关资源
    最近更新 更多