我只将有用的信息放在 Complex.cpp 中。
这是我的问题:我使类变得复杂,这意味着它可以进行复杂的计算。在+
运算符中我想启用 complex + double,但我只能使用 complex + double in main.cpp
。当我使用双变量+复数时出现错误。这是为什么?我可以修复它吗?
复杂的.h
#ifndef COMPLEX_H
#define COMPLEX_H
using namespace std;
class Complex
{
public:
Complex( double = 0.0, double = 0.0 ); // constructor
Complex operator+( const Complex & ) const; // addition
Complex operator-( const Complex & ) const; // subtraction
Complex operator*( const Complex & ) const; // mul
bool operator==( const Complex & ) const;
bool operator!=( const Complex & ) const;
friend ostream &operator<<( ostream & , const Complex& );
friend istream &operator>>( istream & , Complex& );
Complex operator+( const double & ) const;
//Complex &operator+( const double & ) const;
void print() const; // output
private:
double real; // real part
double imaginary; // imaginary part
}; // end class Complex
#endif
复杂的.cpp
Complex Complex::operator+( const Complex &operand2 ) const
{
return Complex( real + operand2.real,imaginary + operand2.imaginary );
} // end function operator+
Complex Complex::operator+(const double &operand2) const
{
return Complex( real + operand2 , this->imaginary );
}
主文件
int main()
{
Complex x;
Complex y( 4.3, 8.2 );
Complex z( 3.3, 1.1 );
double ss = 5;
x = z + ss;
x = ss + z;//this syntax is illegal