gpt4 book ai didi

C++ 类,默认构造函数

转载 作者:行者123 更新时间:2023-11-28 04:53:35 25 4
gpt4 key购买 nike

为了简单明了,我有一个类

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();在类里面,square sq1、sq2 和 sq4 是行不通的。我需要将 square(int s) 初始化为设置为 0 的默认构造函数,并且仅将其用于所有四个正方形。我将如何解决这个问题?

最佳答案

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

square::square(int s = 0) {

side = s; // parameterized constructor with default parameter = 0
}

关于C++ 类,默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47664136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com