继承期间显示未知行为的子类

Child class showing unknown behavior during inheritance

本文关键字:子类 未知 显示 继承      更新时间:2023-10-16

我正在制作一个简单的程序,在这个程序中我创建了一个抽象的shape类,矩形类继承自shape类。我的代码是:

#include <iostream>
using namespace std;
class shape {
protected:
int height;
int width;
public:
shape(int h, int w): height(h), width(w)
{};
virtual double area() = 0;
};
class rectangle: public shape {
public:
rectangle(int h, int w): shape(height, width)
{};
double area() {
return (height * width);
}
};
int main() {
rectangle r1(4, 8);
cout << "Area of rectangle r1 is " << r1.area() << endl;
return 0;
}

输出:

Area of rectangle r1 is 0

它显示面积是0,但它应该显示面积是32。

在构造函数中:

rectangle(int h, int w): shape(height, width) {};

您使用的不是参数hw,而是heightwidth的现有值。由于这些未初始化,使用它们会调用未定义的行为,并且您碰巧看到结果为0。

如果打开警告,编译器应该对此进行抱怨。

你需要做:

rectangle(int h, int w): shape(h, w) {};