在派生类的构造函数初始化中无法访问受保护的函数
Impossible to access protected function in the initialization of the derived class's constructor
我正在尝试实现一个直接从类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
}
};
演示
只能通过派生类访问受保护的成员。
相关文章:
- 继承和友元函数,从基类访问受保护的成员
- C++:为什么无法在派生类中访问受保护的构造函数?
- 如何从其他结构访问受保护的结构变量
- 从模板化父类中的派生内部类访问受保护的成员变量
- 有没有办法通过 main 函数访问受保护的矢量大小而无需将其转换为公共?
- 在派生类的构造函数初始化中无法访问受保护的函数
- 无法通过指针或对象 c++ 访问受保护的成员
- C 继承访问受保护的数据成员
- 访问受保护的成员
- 尝试从基类访问受保护的构造函数时出现错误 C2248
- 如何通过运算符<<的重载访问受保护的功能?C++
- 从公共派生类访问受保护的成员
- Boost单元测试夹具继承测试类,是否可以访问受保护的方法
- 如果我使用强制转换访问受保护的成员,可能会出现什么问题?
- 通过继承访问受保护的成员
- 访问受保护的变量 - 继承和子类的复杂情况
- 为什么我无法从基类的实例访问受保护的成员?
- 访问受保护成员的公共方法
- 通过好友访问受保护的成员
- 从另一个类 C++ 访问受保护的函数