C++之运算符重载

喜欢而已 提交于 2020-02-06 05:23:23

常规: 通过调用方法实现,让 ‘+’实现两个对象(负数)相加

#include <iostream>
class Complex
{
public:
    Complex();
    Complex(double r,double i);
    Complex Complex_add(Complex &d); //普通的函数调用
    //Complex operator+(Complex &d); //运算符重载
    void print();
private:
    double real;
    double imag;
};
Complex::Complex()
{
    real = 0;
    imag = 0;
}
Complex::Complex(double r,double i)
{
    real = r;
    imag = i;
}
Complex Complex::Complex_add(Complex &d)
{
    Complex c;
    c.real = real+d.real;
    c.imag = imag + d.imag;
    return c;
}
Complex Complex::operator+(Complex &d)
{
    Complex c;
    c.real = real + d.real;
    c.imag = imag + d.imag;
    return c;
}
void Complex::print()
{
    std::cout << "(" <<real<<","<<imag<<")"<<std::endl;
}

int main()
{
    Complex a(1,2),b(3,4),c;
    a.print();
    b.print();
    c = a.Complex_add(b);
  //  c = a + b;
    c.print();
    return 0;
}

重载运算符 +,实现两个对象相加

```c
#include <iostream>
class Complex
{
public:
    Complex();
    Complex(double r,double i);
   // Complex Complex_add(Complex &d); //普通的方法调用
    Complex operator+(Complex &d); //运算符重载
    void print();
private:
    double real;
    double imag;
};
Complex::Complex()
{
    real = 0;
    imag = 0;
}
Complex::Complex(double r,double i)
{
    real = r;
    imag = i;
}
Complex Complex::Complex_add(Complex &d)
{
    Complex c;
    c.real = real+d.real;
    c.imag = imag + d.imag;
    return c;
}
Complex Complex::operator+(Complex &d)
{
    Complex c;
    c.real = real + d.real;
    c.imag = imag + d.imag;
    return c;
}
void Complex::print()
{
    std::cout << "(" <<real<<","<<imag<<")"<<std::endl;
}

int main()
{
    Complex a(1,2),b(3,4),c;
    a.print();
    b.print();
    //= a.Complex_add(b);
    c = a + b;
    c.print();
    return 0;
}

使用友元函数实现运算符重载:

#include <iostream>

class Complex
{
public:
    Complex();
    Complex(double r,double i);
    Complex Complex_add(Complex &d); //普通的函数调用
  //  Complex operator+(Complex &d); //运算符重载
    friend Complex operator+(Complex &c,Complex &d); //运算符重载
    void print();
private:
    double real;
    double imag;
};

Complex::Complex()
{
    real = 0;
    imag = 0;
}
Complex::Complex(double r,double i)
{
    real = r;
    imag = i;
}
Complex Complex::Complex_add(Complex &d)
{
    Complex c;
    c.real = real + d.real;
    c.imag = imag + d.imag;
    return c;
}
//这里是,友元函数的实现,不需要:域作用符,但友元函数会破坏类的封装性,所以一般不推荐
Complex operator+(Complex &a,Complex &b)
{
    Complex c;
    c.real = a.real + b.real;
    c.imag = a.imag + b.imag;
    return c;
}
void Complex::print()
{
    std::cout << "(" <<real<<","<<imag<<")"<<std::endl;
}

int main()
{
    Complex a(1,2),b(3,4),c;
    a.print();
    b.print();
    c = a + b;
    c.print();
    return 0;
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!