操作符重载“+”复杂/双 [英] operator overloading "+" for types complex/double
问题描述
我只把有用的信息放在Complex.cpp中。
I put only the useful information in Complex.cpp.
这里是我的问题:我做了类复杂,这意味着它可以复杂计算。
在 +
运算符中我想启用复杂+双,但我只能在 main.cpp
。当我使用双变量+复合体时有一个错误。这是为什么?我可以修复吗?
Here is my problem: I made the class complex which means it can calculate in complex.
In the +
operator I want to enable complex + double, but I can only use complex + double in main.cpp
. When I use a double variable + complex there is an error. Why is that? Can I fix it?
#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
Complex.cpp
Complex.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 );
}
main.cpp
main.cpp
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
推荐答案
为了允许你的类显示为右手操作数,操作符需要是非成员。因为(在这种情况下)它需要访问私有成员,所以它必须是一个朋友:
In order to allow your class to appear as the right hand operand, the operator needs to be a non-member. Since (in this case) it needs access to the private members, it will have to be a friend:
class Complex {
// ...
friend Complex operator+(double lhs, const Complex & rhs);
};
Complex operator+(double lhs, const Complex & rhs) {
return Complex(lhs+rhs.real, rhs.imaginary);
}
或者,因为你已经有一个成员采用反向的参数,和添加是对称的,你可以定义一个非成员,非朋友函数:
Alternatively, as you already have a member taking the arguments the other way round, and addition is symmetric, you could define a non-member, non-friend function:
Complex operator+(double lhs, const Complex& rhs) {
return rhs + lhs;
}
这篇关于操作符重载“+”复杂/双的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!