gpt4 book ai didi

c++ - C++ 语言中的构造函数

转载 作者:行者123 更新时间:2023-12-04 17:09:42 24 4
gpt4 key购买 nike

代码如下:

#include<iostream>
using namespace std;

class Rectangle
{
private :
int _width;
int _height;
public :
Rectangle()
: _width{},_height{}
{}
Rectangle(int initial_w, int initial_h)
: _width{initial_w}, _height{initial_h}
{}
int get_width(){return _width;}
};

int main()
{
Rectangle a;
Rectangle(2,3);
cout<<a.get_width()<<endl;
}

我不明白为什么它返回 0,我认为它应该是 2。请帮忙!!!!!!

最佳答案

在您的 main 方法中,您创建了一个 Rectangle a;,它会调用您的默认构造函数 Rectangle()。然后在下一行中,您使用 Rectangle(2,3); 创建一个临时元素,它调用您的初始化构造函数 Rectangle(int initial_w, int initial_h),但它是立即丢弃,因为您尚未将其分配给变量。最后,您输出默认构造的变量 a。

看起来你想要实现的是这样的:

int main()
{
Rectangle a(2, 3);
cout << a.get_width() << endl;
}

关于c++ - C++ 语言中的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60448884/

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