class Complex
{
private:
float re;
float im;
public:
Complex(float r = 0.0, float i = 0.0) : re(r), im(i){}
friend Complex operator+(Complex c1, Complex c2);
};
Complex operator+(Complex c1, Complex c2)
{
return Complex(c1.re + c2.re, c1.im + c2.im);
}
int main()
{
Complex c1(1,2);
Complex c2(1,2);
Complex c3;
c3 = 1.0 + c2;
}
我不清楚为什么这样可行,因为似乎 float 1.0是运算符中的一个参数而c2是另一个参数。现在我被告知这是好的,因为构造函数被调用,这是否有效?我们怎么知道,1.0分配给 r 而不是 i ??
现在以下是不正确的,我问为什么?
class Complex
{
private:
float re;
float im;
public:
Complex(float r = 0.0, float i = 0.0) : re(r), im(i){}
Complex operator+(Complex c1);
};
Complex Complex::operator+(Complex c1)
{
return Complex(this->re + c1.re, this->im + c1.im);
}
int main()
{
Complex c1(1,2);
Complex c2(1,2);
Complex c3;
c3 = 1.0 + c2;
}
这不起作用,是因为1.0不是复杂的对象,为什么不在这里初始化构造函数来创建一个re = 1.0,im = 0.0的对象?正如问题的第一部分所假设的那样?
error: no match for 'operator+' in '1.0e+0 + c2'|
答案 0 :(得分:2)
当您将{:name=>"Nate", :city=>"San Diego"}
Hash
Nate lives in San Diego
{: nameI" Nate:ET: cityI"San Diego;T
String
Completed 500 Internal Server Error in 349ms
TypeError - no implicit conversion of Symbol into Integer:
实现为成员函数时,运算符的LHS必须是operator+
类型的对象。
当您将Complex
实现为非成员函数时,只要有一种方法可以使用隐式转换从中构造operator+
类型的对象,则运算符的LHS可以是任何内容。
这是非成员函数版本工作的原因,而成员函数版本没有。
答案 1 :(得分:1)
在第一种情况下,调用构造函数,因为
Complex(float r = 0.0, float i = 0.0) : re(r), im(i){}
当没有传递第二个参数时,就像转换一样。因此,任何float
都可以转换为Complex
。
在第二种情况下,如果运算符是成员函数:
Complex Complex::operator+(Complex c1)
必须在Complex
类型的对象上调用它。但是,当你写:
c3 = 1.0 + c2;
+
的{{1}}运算符将以float
作为参数调用(“将”,因为没有此类运算符)。相反,如果你写:
c2
它应该有效,因为现在调用c3 = c2 + 1.0;
的{{1}}运算符。它希望+
作为参数,c2
可以转换,所以这可以工作。
答案 2 :(得分:1)
感谢分享问题,
对于第一部分,我正在调试代码并发现对于点c3 = 1.0 + c2; C ++创建Complex的对象(如预期的那样),但带有参数(1.0和0)。如下所示,调试信息我已粘贴在下面。它类似于创建临时复杂变量,调用默认构造函数和参数传递为1.0和0.又称复杂(1,0)因此它工作正常。
断点1,main()在probl.cpp:24
24 c3 = 1.0 + c2;
(gdb)s
在probl.cpp上复杂::复杂(这= 0x23cc68,r = 1,i = 0):10
10复数(float r = 0.0,float i = 0.0):re(r),im(i){}
正如其他人在第二部分中提到的那样,“+”运算符是Complex类的一部分,因此c3 = 1.0 + c2;如果将1.0转换为正确的复杂类实例,则仅调用+运算符。因此它给出了编译错误。 要解决此问题,您可以将代码更改为
c3 =复合体(1.0)+ c2;
这里使用默认值re = 1和im = 0创建复杂类的临时对象,然后将operator +调用到此临时对象。 希望这会有所帮助。