为了保持简单和切题,我有一个类
class square
{
public:
square(int s); // parameterized constructor with default parameter = 0
square();
private:
int side; // holds the side of the square (whole number)
};
square::square() {
side = 0;
}
square::square(int s){
side = 0; // parameterized constructor with default parameter = 0
}大体上,我有以下几点:
int main()
{
square sq1;// declare 4 objects of type square named sq1, sq2, sq3, and sq4 initializing the third one to 10
square sq2;
square sq3(10);
square sq4;
}问题是,如果我在类中注释掉square();,sq1、sq2和sq4就不能工作了。我需要将square(int s)初始化为设置为0的默认构造函数,并且仅将其用于所有四个正方形sq。我该如何解决这个问题?
发布于 2017-12-06 07:14:46
完全删除默认构造函数(square(); )并修改参数化构造函数定义,如下所示。
square::square(int s = 0) {
side = s; // parameterized constructor with default parameter = 0
}发布于 2017-12-06 07:19:27
在任何情况下,您都必须定义一个默认构造函数。来自C++ (2017)标准(15.1构造器)
4类X的默认构造函数是类X的构造函数,对于X类,每个不是函数参数包的参数都有一个默认参数(包括没有参数的构造函数的情况)。如果X类没有用户声明的构造函数,则没有参数的非显式构造函数将被隐式声明为默认值(11.4)。隐式声明的默认构造函数是其类的内联公共成员。
因此,要使带参数的构造函数成为默认构造函数,只需在构造函数的声明中提供默认参数。例如
class square
{
public:
square(int s = 0 ); // parameterized constructor with default parameter = 0
private:
int side; // holds the side of the square (whole number)
};构造函数本身可以定义为
square::square( int s ) : side( s )
{
}还可以使用函数说明符explicit声明构造函数,以防止从类型int到类型square的隐式转换。
class square
{
public:
explicit square(int s = 0 ); // parameterized constructor with default parameter = 0
private:
int side; // holds the side of the square (whole number)
};https://stackoverflow.com/questions/47664136
复制相似问题