[英]Default constructor in derived classes
i am going over my old exams to study for finals and have noticed some stuff I still do not understand. 我正在过去的考试中学习期末考试,并注意到一些我仍然不了解的内容。
class Shape
{
private:
int center_x, int center_y;
public:
Shape (int x, int y) : center_x(x), center_y(y); {} //constructor initializer
}
class Rectangle : public Shape
{
private:
int length, width;
public:
Rectangle(): //this is where i have trouble, I am supposed to fill in missing code here
//but shape does not have a default constructor, what am i supposed to fill in here?
Rectangle (int x, int y, int l, int w) : Shape(x,y);{length = l; width = w;}
}
Thanks 谢谢
There are two approaches. 有两种方法。 Either you call the base class construcor in the mem-initializer list of the default constructor with some default values as for example (I use zeroes as the default values): 您可以在默认构造函数的mem-initializer列表中调用基类construcor,例如使用一些默认值(我将零用作默认值):
Rectangle() : Shape( 0, 0 ), length( 0 ), width( 0 ) {}
Or you can delegate all the work from the default constructor to the constructor with parameters. 或者,您可以将所有工作从默认构造函数委派给带参数的构造函数。
For example 例如
Rectangle() : Rectangle( 0, 0, 0, 0 ) {}
Take into account that class definitions shall be ended with semicolon.:) 考虑到类定义应以分号结尾。
You're asking the wrong question. 您问错了问题。 You should be asking 你应该问
What should a default constructed
Rectangle
be? 默认构造的Rectangle
应该是什么?
Once you answer this question, one of the following will happen: 回答此问题后,将发生以下情况之一:
Shape
base 清楚如何初始化Shape
基础 Rectangle
should not have a default constructor 您将意识到Rectangle
不应该具有默认构造函数 You can assume that no coordinates are defined for your default rectangle. 您可以假定没有为默认矩形定义坐标。 So it would be: 因此它将是:
Rectangle(): Shape(x,y) , length(0), width(0) { }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.