C++ 派生类无法访问 protected 成员,除非使用默认构造函数

标签 c++

在构造函数中初始化字段:

class Shape{
protected: 
float width,height;
public:
Shape()
{
    width = 13.2;
    height = 3.2;
}
}

但是,当使用带参数的构造函数时,代码将不再编译:

class Shape{
protected: 
float width,height;
public:
Shape(float w, float h)
{
    width = w;
    height = h;
}
}

三角形类:

class Triangle : public Shape{
public:
float area()
{
    return (width * height / 2);
}

主要功能如下:

int main() {
Shape s = Shape();
Triangle tri;

std::cout << tri.area() << std::endl;
return 0;

编译并输出结果: 21.12

但是,当使用带参数的构造函数时Shape s = Shape(13.2,3.2); 看来 Triangle 对象 tri 无法再访问 Shape 类的宽度和高度。

最佳答案

问题在于,通过使用参数定义 Shape 的构造函数,您禁用了 Shape 的默认构造函数(或更准确地说,将其定义为已删除)。由于 Triangle 没有定义默认构造函数,因此它也会被标记为已删除。

您需要定义 Shape 的默认构造函数,或者定义 Triangle 的构造函数,它将使用参数调用 Shape 的构造函数wh

关于C++ 派生类无法访问 protected 成员,除非使用默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65706101/

相关文章:

c++ - 共享指针集合和常用方法

c++/openframeworks - 如何在开放框架程序之间切换

c++ - 审核 bash RPG 的 bash 命令

c++ - 这是对多态性的适当使用吗?

c++ -++i 与 i++ : is there any difference on any modern compiler?

c++ - 如何在依赖的静态库中链接 Boost

c++ - SFML 不显示 Sprite

c++ - gdb:如何调用 operator char const*()?

c++ - 在 Windows DLL 函数参数中使用 float

c++ - 为什么人们不在 C++ 中的头文件名称中使用大写字母?