gpt4 book ai didi

c++ - 未定义时如何返回值?

转载 作者:行者123 更新时间:2023-11-30 01:57:01 24 4
gpt4 key购买 nike

我正在尝试理解重载运算符,而且我盯着它看的时间比我想承认的要长。我相信除了 operator+ 成员之外,我了解类里面的所有内容。我试图用大量可用信息自学,但我找不到任何信息可以向我解释我在这里看到的内容——而且我坚信,如果我了解某些东西是如何工作的,那么我就可以更好地使用它。

所以,大多数情况下,我的困惑在于编译器如何知道选择哪个临时变量。 (temp.x 或 temp.y)我意识到 main() 正在请求 c.x 和 c.y,但 operator+ 似乎正在返回尚未定义的内容。没有三元运算符或任何可以让它选择返回哪一个的东西。

#include <iostream>
using namespace std;

class CVector {
public:
int x,y;
CVector () {};
CVector (int,int);
CVector operator + (CVector);
};

CVector::CVector (int a, int b) {
x = a;
y = b;
}

CVector CVector::operator+ (CVector param) {
CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return (temp);
}

int main () {
CVector a (3,1);
CVector b (1,2);
CVector c;
c = a + b;
cout << c.x << "," << c.y;
return 0;
}

最佳答案

So, mostly, my confusion lies with how the compiler knows which variable of temp to choose.

我真的不明白你的意思。编译器没有选择要返回的 temp 变量。 tempCVector 类型的对象。它包含两个数据成员,xy。当使用此行创建时,这些成员作为 temp 的一部分存在:

CVector temp;

然后,当你这样做时:

return temp;

编译器没有什么可以选择的。它返回整个对象,其中包括一个复合对象中的 xy

在你的主函数中,这一行:

c = a + b;

ab 上调用operator+。然后将返回值(temp)赋值(operator=)给c。由于您还没有定义自定义赋值运算符,默认的运算符开始使用,它只是执行从 tempc 的成员赋值。因此,temp.x 被分配给 c.xtemp.y 被分配给 c.y

对于您的类,默认赋值运算符看起来像(或具有相同的操作语义),如果它被写出来的话:

CVector & CVector::operator=(const CVector & rhs)
{
this->x = rhs.x;
this->y = rhs.y;
return *this;
}

关于c++ - 未定义时如何返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19238086/

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