【发布时间】:2019-12-29 00:34:27
【问题描述】:
我正在尝试实现一个类Union,它直接继承自类Shape(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;
}
但是,当我在Union 构造函数的初始化列表中调用get_center() 时,出现错误说“get_center() 是Shape 的受保护成员”。
谁能解释我为什么不能从子类Union(应该继承该函数)调用get_center()?
谢谢!
P.S.:如果我将函数get_center()设置为public,就没有错误了。
【问题讨论】:
-
你真的要使用私有继承吗?
-
@NeilButterworth 是的。不管怎样,当我写
class Union: public Shape {...}时,问题仍然存在。 -
@Jarod42 但
Union是Shape的派生类。我不应该访问get_center()函数吗? -
来自
Union,是的,不是来自Shape。 -
This 可能会有所帮助
标签: c++ inheritance constructor initialization protected