gpt4 book ai didi

c++ - 我很困惑为什么在 C++ 中返回构造函数是合法的

转载 作者:行者123 更新时间:2023-11-28 05:45:09 26 4
gpt4 key购买 nike

例如:

#include<iostream>
using namespace std;
class exa{
private:
int a;
public:
exa(int b = 0):a(b){}
exa Add(exa obj){ return exa(a+obj.geta() ); } //What happened over there?
int geta(){return a;}
};
int main()
{
exa c1(2),c2;
c2.Add(c1);
cout << c2.geta() << endl;
return 0;
}

最佳答案

请注意,您正在将参数传递给构造函数。所以你不是返回构造函数,而是调用它来构造类的对象。因为您没有使用 new,所以对象的存储是在堆栈上分配的。

这里,Add 方法返回(按值)exe 类的对象。

实际上,它在 main 中的使用方式实际上并没有做任何事情,因为 c2.Add(c1) 的结果被忽略了。

如果您编写了 c2 = c2.Add(c1),那么新对象将被复制(使用默认赋值 operator=)到 c2,您应该会看到输出 2

关于c++ - 我很困惑为什么在 C++ 中返回构造函数是合法的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36368443/

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