【发布时间】:2020-09-16 12:47:18
【问题描述】:
所以我有一个下面给出的类的方法,它使用运算符重载将两个复数相乘:
Complex operator*(Complex &c2) {
Complex temp;
temp.realPart = realPart * c2.realPart - (imaginaryPart * c2.imaginaryPart);
temp.imaginaryPart = (realPart * c2.imaginaryPart) + (imaginaryPart * c2.realPart);
return temp;
}
这似乎工作正常。但是,当我将成员函数头更改为:
Complex& operator * (Complex &c2) { // Adding & after the class name.
程序没有崩溃,但无法计算答案/程序上的光标闪烁一段时间后结束。类名后面的 & 是什么意思?我已经看到它在返回 this 指针时被使用。
【问题讨论】:
-
返回类型是对对象的引用。
-
您正在返回对局部变量的引用。引用是自动取消引用指针的语法糖。在幕后,您将返回一个指向对象的指针,该对象在方法返回时被释放。
-
operator*应该返回一个新对象,所以返回一个引用是错误的。此外,输入参数应通过const引用传递:Complex operator*(const Complex &c2) -
意识到原来的作品是因为您返回的是
temp的副本,而不是temp本身,而参考版本返回的是reference i> 到temp,它位于方法内部的堆栈中。但是返回之后,temp已经不存在了。这个运算符重载的调用者引用了不再存在的东西,因此出现了奇怪的未定义行为。
标签: c++ overloading pass-by-reference