首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++类,默认构造函数

C++类,默认构造函数
EN

Stack Overflow用户
提问于 2017-12-06 07:05:04
回答 2查看 140关注 0票数 0

为了保持简单和切题,我有一个类

代码语言:javascript
复制
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
}

大体上,我有以下几点:

代码语言:javascript
复制
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。我该如何解决这个问题?

EN

回答 2

Stack Overflow用户

发布于 2017-12-06 07:14:46

完全删除默认构造函数(square(); )并修改参数化构造函数定义,如下所示。

代码语言:javascript
复制
square::square(int s = 0) {

    side = s; // parameterized constructor with default parameter = 0
}
票数 1
EN

Stack Overflow用户

发布于 2017-12-06 07:19:27

在任何情况下,您都必须定义一个默认构造函数。来自C++ (2017)标准(15.1构造器)

4类X的默认构造函数是类X的构造函数,对于X类,每个不是函数参数包的参数都有一个默认参数(包括没有参数的构造函数的情况)。如果X类没有用户声明的构造函数,则没有参数的非显式构造函数将被隐式声明为默认值(11.4)。隐式声明的默认构造函数是其类的内联公共成员。

因此,要使带参数的构造函数成为默认构造函数,只需在构造函数的声明中提供默认参数。例如

代码语言:javascript
复制
class square
{
public:
    square(int s = 0 ); // parameterized constructor with default parameter = 0

private:
    int side; // holds the side of the square (whole number)
};

构造函数本身可以定义为

代码语言:javascript
复制
square::square( int s ) : side( s )
{
}

还可以使用函数说明符explicit声明构造函数,以防止从类型int到类型square的隐式转换。

代码语言:javascript
复制
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)
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47664136

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档