したがって、複素数の基本的な算術演算を実装するように演算子をオーバーロードするように求められています。私は+、 - 、そして=働いていますが、私は正しいロジックを持っていると思っていても働くことはできません。複素数の*演算子のオーバーロード(C++)
私のコードで何が問題になっていますか?
#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;
};
通常、2つのパラメータを取る演算子は、メンバー以外の自由な関数として実装する必要があります。これにより、LHSオペランドの暗黙の変換が可能になります。 –
私はC++に年齢が合っていると思っていました。なぜ自分自身を実装するのが教育のことなのでしょうか?カスタム固有の数学的最適化を後で望んでいますか? – Swift