因此我被要求重载运算符来实现复数的基本算术。我已经得到+, - 和=工作,但即使我认为我有正确的逻辑,我似乎也无法工作。
我的代码出了什么问题?
#ifndef COMPLEX_HPP
#define COMPLEX_HPP
#include <string>
class Complex
{
public:
Complex(double = 0.0, double = 0.0); // default constructor
Complex add(const Complex&) const; // function add
Complex subtract(const Complex&) const; // function subtract
Complex multiply(const Complex&) const; // function multiply
std::string toString() const; // return string representation
void setComplexNumber(double, double); // set complex number
void operator=(const Complex& obj)
{
(*this).realPart = obj.realPart;
(*this).imaginaryPart = obj.imaginaryPart;
}
Complex operator+(const Complex& obj)
{
Complex tmp_obj = *this;
tmp_obj.realPart = tmp_obj.realPart + obj.realPart;
tmp_obj.imaginaryPart = tmp_obj.imaginaryPart + obj.imaginaryPart;
return tmp_obj;
}
Complex operator-(const Complex& obj)
{
Complex tmp_obj = *this;
tmp_obj.realPart = tmp_obj.realPart - obj.realPart;
tmp_obj.imaginaryPart = tmp_obj.imaginaryPart - obj.imaginaryPart;
return tmp_obj;
}
Complex operator*(const Complex&obj)
{
Complex tmpObj = *this;
tmpObj.realPart = (tmpObj.realPart * obj.realPart) - (tmpObj.imaginaryPart * obj.imaginaryPart);
tmpObj.imaginaryPart = (tmpObj.realPart * obj.imaginaryPart) + (tmpObj.imaginaryPart * obj.realPart);
return tmpObj;
}
private:
double realPart;
double imaginaryPart;
};
答案 0 :(得分:1)
一旦开始覆盖tmpObj
(具体而言,tmpObj.realPart
),您就会丢失原始值。所以请勿从tmpObj
读取,而是从*this
:
tmpObj.realPart = realPart * obj.realPart - imaginaryPart * obj.imaginaryPart;
// ^^^^^^^^ ^^^^^^^^^^^^^
tmpObj.imaginaryPart = realPart * obj.imaginaryPart + imaginaryPart * obj.realPart;
// ^^^^^^^^ ^^^^^^^^^^^^^
答案 1 :(得分:1)
operator*()
的实施基本上是。
Complex operator*(const Complex&obj)
{
Complex tmpObj = *this;
tmpObj.realPart = (tmpObj.realPart * obj.realPart) - tmpObj.imaginaryPart * obj.imaginaryPart);
tmpObj.imaginaryPart = (tmpObj.realPart * obj.imaginaryPart) + (tmpObj.imaginaryPart * obj.realPart);
return tmpObj;
}
问题是第一个语句修改了tmpObj.realPart
,第二个语句继续进行,就像tmpObj.realPart
没有被修改一样。
修复很简单:不要在作业的右侧使用tmpObj
。
Complex operator*(const Complex&obj)
{
Complex tmpObj; // your default constructor initialises to (0.0,0.0)
tmpObj.realPart = (realPart * obj.realPart) - (imaginaryPart * obj.imaginaryPart);
tmpObj.imaginaryPart = (realPart * obj.imaginaryPart) + (imaginaryPart * obj.realPart);
return tmpObj;
}