【发布时间】:2015-01-11 08:57:29
【问题描述】:
我正在尝试创建一个 Polygon 类以及一个继承第一个的 Rectangle 和 Triangle。 Polygon 类具有高度和宽度变量,我希望它们在构造函数中被赋予值。然后,矩形和三角形有面积计算方法。然后,我使用 main() 来举一些例子。我用:
#include <iostream>
using namespace std;
class Polygon {
public:
Polygon(int, int);
protected:
int height;
int width;
};
class Rectangle: public Polygon {
public:
void calc_area();
};
class Triangle: public Polygon {
public:
void calc_area();
};
Polygon::Polygon(int a, int b) {
height = a;
width = b;
}
void Rectangle::calc_area() {
cout << "Rectangle area: " << (height*width) << endl;
}
void Triangle::calc_area() {
cout << "Triangle area: " << (height*width/2) << endl;
}
int main() {
Rectangle s1(5, 2);
Triangle s2(5, 2);
s1.calc_area();
s2.calc_area();
}
但是,虽然在我的新手眼中一切看起来都不错,但我得到了一系列错误:
12 base Polygon',类中只有非默认构造函数,没有构造函数`
36 没有匹配函数调用`Rectangle::Rectangle(int, int)
37 没有匹配函数调用`Triangle::Triangle(int, int)'
谁能给我一些建议?正如所见,我对 C++ 很陌生...
【问题讨论】:
-
向 Polygon 类添加默认构造函数。
-
确实我的许多问题都解决了,但我仍然收到最后一个 38 错误
标签: c++ inheritance