我正在嘗試編寫一個可以使用複數運算的程序。然而我被困與符*我無法弄清楚如何使這兩個情況下工作:運算符*超載C++
First:
c = 10 * d;
cout << c << endl;
Second:
c = d * 10;
cout << c << endl;
這是我的頭:
class Complex
{
private:
double Real, Imag;
public:
Complex() : Real(), Imag()
{
}
//----------------------------------------------------------------------
Complex (double Real) //Initialization with only one variable
{
this->Real = Real;
Imag = 0;
}
//----------------------------------------------------------------------
Complex (double Real, double Imag) //Complete initialization
{
this->Real = Real;
this->Imag = Imag;
}
//----------------------------------------------------------------------
Complex & operator = (const Complex &s)
{
Real = s.Real;
Imag = s.Imag;
return *this;
}
//----------------------------------------------------------------------
Complex operator * (Complex s) // (r + i) * x
{
this->Real *= s.Real;
this->Imag *= s.Real;
return *this;
}
//----------------------------------------------------------------------
Complex & operator *= (Complex s) //Reference
{
Real *= s.Real;
Imag *= s.Imag;
return *this;
}
//----------------------------------------------------------------------
friend Complex operator * (Complex s1, Complex s2);
//----------------------------------------------------------------------
friend ostream &operator << (ostream &s, const Complex &c)
{
s << c.Real << " + " << c.Imag;
return s;
}
};
//Out of class functions
inline Complex operator * (Complex s1, Complex s2) // x * (r + i)
{
s2.Real *= s1.Real;
s2.Imag *= s1.Real;
return s2;
}
//----------------------------------------------------------------------
bool Complex::operator == (const Complex &s) const
{
return (this->Real == s.Real && this->Imag == s.Imag);
}
//----------------------------------------------------------------------
#endif /* __Complex_H__ */
我的想法是使用運營商內部類第二第一種情況,外部情況。但我得到的錯誤:
error: ambiguous overload for 'operator*' in 'd * 10
如何清楚地向編譯器指出哪些重載使用?
我主要是:
#include <iostream>
#include "complex.h"
using namespace std;
int main()
{
Complex c, d(3, 5);
c = 10 * d;
cout << c << endl;
c = d * 10;
cout << c << endl;
}
你的實際代碼是什麼樣的? 'c = 10 * d;'本身不會編譯。 – AndyG
與你的問題無關,但你的'operator *'的行爲與'operator * ='完全一樣,這是不正確的。而且,爲什麼你需要兩種類型的重載和超類重載?似乎編譯器無法決定要調用哪一個。 –
我的想法是讓這兩種情況都起作用。我不知道如何在課堂上解決它 – Aghero