C++ - 重载运算符

2016-01-16  本文已影响105人  Mitchell

运算符


运算符重载

class Complex{
    public:
          Complex(double r = 0.0,double i = 0.0){
                real = r;
                imaginary = i;
          }
          double real;
          double imaginary;
};
Complex operator+ (const Complex &a,cost Complex &b)
{
  return Complex(a.real+b.real,a.imaginary+b.imaginary);
}//类名(参数表)就代表一个对象
Complex a(1,2),b(2,3),c;
c = a + b;//相当于什么?
//相当于调用了:
operator+(a,b);
class Complex{
    public:
          Complex(double r = 0.0,double m = 0.0);
                        real(r),imaginary(m){  }
          Complex operator+ (const Complex &);
          Complex operator- (const Complex &);
    private:
          double real;
          double imaginary;
};
Complex Complex::operator+(const Complex & operand2){
    return Complex(real +operand2.real,imaginary+ operand2.imaginary);
}
Complex Complex::operator-(const Complex & operand2){
    return Complex(real -operand2.real,imaginary- operand2.imaginary);
}
int main(){
    Complex x,y(4.3,8.2),z(3.3,1.1);
    x = y + z;
    x = y - z;
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读