我们什么时候需要一个默认的构造函数? [英] When do we need to have a default constructor?
问题描述
我的问题很简单。我们什么时候需要一个默认的构造函数?
请参考下面的代码:
类Shape
{
int k;
public:
Shape(int n):k(n){}
〜Shape(){}
};
类Rect:public Shape
{
int l;
public:
Rect(int n):l(n)
{} //错误C2512:'Shape':没有合适的默认构造函数
〜Rect(){}
};
-
为什么编译器不生成零参数默认构造函数根据我的知识,如果一个类(Rect)派生自另一个类(Shape),它有默认的构造函数(隐式的(隐式的),在类Rect中隐含的
<生成或显式提供),默认构造函数应由编译器生成。
如果您使用参数创建自己的构造函数,则不会合成默认构造函数。因为你给了 Shape
一个你自己的构造函数,你必须显式地写出一个默认的 Shape
构造函数:
类Shape
{
int k;
public:
Shape():k(0){}
Shape(int n):k(n){}
};
(你可以省略空的〜Rect code>定义,因为这些将被合成。)
但是,它看起来像我不喜欢构造函数。有 Rect
正确构建形状
基础:
class Shape
{
int area; //我不得不猜测这个成员的意思。什么是k?
public:
Shape(int n):area(area){}
};
class Rect:public Shape
{
int l;
public:
Rect(int l,int w):Shape(l * w),l(l),w(w){}
}
另请注意,此示例为引用为OO的滥用。请考虑您是否真的需要继承。
My question is simple. When do we need to have a default constructor? Please refer to the code below:
class Shape
{
int k;
public:
Shape(int n) : k(n) {}
~Shape() {}
};
class Rect : public Shape
{
int l;
public:
Rect(int n): l(n)
{} //error C2512: 'Shape' : no appropriate default constructor available
~Rect() {}
};
Why is the compiler not generating the zero argument default constructor implicitly in the class Rect?
As per my knowledge, if a class (Rect) is derived from another class (Shape) that has default constructor (either implicitly generated or explicitly provided), the default constructor should be generated by the compiler.
A default constructor is not synthesised if you created your own constructor with arguments. Since you gave Shape
a constructor of your own, you'd have to explicitly write out a default Shape
constructor now:
class Shape
{
int k;
public:
Shape() : k(0) {}
Shape(int n) : k(n) {}
~Shape() {}
};
(You can leave out the empty ~Rect() {}
definitions, as these will be synthesised.)
However, it looks to me like you don't want a default constructor for Shape here. Have Rect
construct the Shape
base properly:
class Shape
{
int area; // I've had to guess at what this member means. What is "k"?!
public:
Shape(int n) : area(area) {}
};
class Rect : public Shape
{
int l;
public:
Rect(int l, int w) : Shape(l*w), l(l), w(w) {}
};
Also note that this example is oft cited as an abuse of OO. Consider whether you really need inheritance here.
这篇关于我们什么时候需要一个默认的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!