运算符 * 重载 C++

operator * overload c++

我正在尝试编写一个可以处理复数的程序。但是我被 operator * 困住了,我不知道如何让这两种情况起作用:

First:
c = 10 * d;
cout << c << endl;
Second:
c = d * 10;
cout << c << endl;

这是我的 header:

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__ */

我的想法是在 class 内部使用运算符处理第二种情况,在外部使用运算符处理第一种情况。但是我得到了错误:

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;
}

在第一种情况下,friend 非 class 方法的调用没有歧义,因为第一个参数不是 Complex 但可以使用 doubleComplex构造函数

第二种情况,可以应用成员方法*friend函数,所以报错

不需要使用 2 个 Complex 对象的友元运算符。只有当第一个参数是一个非class对象/一个class对象时,它才有用set/change *

的行为

你最好:

friend Complex operator * (double s1, const Complex &s2);

备注:

  • 标准库有一个很好的std::complex实现。
  • 最好使用常量引用而不是值参数传递
  • 重载成员 operator*(double s1) 会很有趣,以避免在您想乘以实数值时转换为 Complex