在构造函数中初始化字段:
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
的构造函数w
和 h
。
关于C++ 派生类无法访问 protected 成员,除非使用默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65706101/