【发布时间】:2013-05-10 04:48:47
【问题描述】:
我刚刚进入派生类,我正在研究著名的Shape 类。 Shape 是基类,那么我有三个派生类:Circle、Rectangle 和 Square。 Square 是 Rectangle 的派生类。我想我需要将派生类构造函数中的参数传递给基类构造函数,但我不确定该怎么做。我想在创建形状时设置它们的尺寸。这是我的基类和一个派生类:
Shape(double w = 0, double h = 0, double r = 0)
{
width = w;
height = h;
radius = r;
}
class Rectangle : public Shape
{
public:
Rectangle(double w, double h) : Shape(double w, double h)
{
width = w;
height = h;
}
double area();
void display();
};
我在正确的轨道上吗?我收到以下编译器错误:expected primary expression before "double",在每个派生构造函数中。
【问题讨论】:
-
对于您的编译器错误,您必须删除冒号后
Shape(double w, double h)中的doubles,因为您实际上是在调用基类的构造函数。 -
另外,考虑使用成员初始化器来初始化 Shape 的成员,而不是赋值,即让 Shape 构造函数看起来像这样:
Shape(double w = 0, ...) : width(w), height(h), radius(r) {}。 -
通用形状的半径是什么意思?也许你需要重新考虑你的班级设计。
标签: c++ class inheritance constructor