ric*_*boy 2 c++ polymorphism inheritance
我正在读我的旧考试去学习决赛,并注意到一些我仍然不理解的东西.
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;}
}
Run Code Online (Sandbox Code Playgroud)
谢谢
有两种方法.您可以在默认构造函数的mem-initializer列表中调用基类construcor,并使用一些默认值(例如,我使用零作为默认值):
Rectangle() : Shape( 0, 0 ), length( 0 ), width( 0 ) {}
Run Code Online (Sandbox Code Playgroud)
或者,您可以将默认构造函数中的所有工作委托给带参数的构造函数.
例如
Rectangle() : Rectangle( 0, 0, 0, 0 ) {}
Run Code Online (Sandbox Code Playgroud)
考虑到类定义应以分号结束.:)
| 归档时间: |
|
| 查看次数: |
479 次 |
| 最近记录: |