重载运算符+定义非成员、非友元函数

如果想要访问类中的私有变量则需要创建成员函数来访问

#include <iostream>
using namespace std;
class Complex  {
public: 
Complex(){real=0;imag=0;} 
Complex(double r,double i){real=r;imag=i;} 
double get_real(); 
double get_imag();
void display();
private:   
double real;    
double imag;
};
double Complex::get_real()
{
   return real;
}
double Complex::get_imag()
{
    return imag;
}
void Complex::display()
{
    cout<<"("<<real<<","<<imag<<"i"<<")"<<endl;
}

Complex operator+(Complex &c1,Complex &c2)
{
    return Complex(c1.get_real()+c2.get_real(),c1.get_imag()+c2.get_imag());
}
int main()
{
    Complex c1(2,4),c2(6,10),c3;
    c3 = c1+c2;
    cout<<"c3=";
    c3.display();
    return 0;
}

posted @ 2022-07-31 17:11  鹅城小铁匠  阅读(55)  评论(0)    收藏  举报
Fork me on GitHub