标签:open cte operator close 技术 str ted 形参 turn
题目一:不用运算符重载,实现两个复数的相加。产生复数对象c1,c2,得到c3=c1+c2,并打印输出c3。
#include <iostream> using namespace std; class complex { public: complex(){real=0;imag=0;} complex(double r,double i):real(r),imag(i){} complex complex_add(complex & c2); void display(); private: double real,imag; }; complex complex::complex_add(complex & c2) { complex c; c.real=real+c2.real;//谁调用就是谁的this c.imag=imag+c2.imag; return c; } void complex::display() { cout<<"("<<real<<","<<imag<<")"<<endl; } int main() { complex c1(3.5,4.5),c2(3.6,4.4),c3; c3=c1.complex_add(c2); c3.display(); return 0; }
运算符重载:
函数类型 operator 运算符名称(形参列表);
operator+运算符名称,可以理解为函数名
complex complex::operator+(complex &c2)
{ return complex(real+c2.real,imag+c2.imag); }
#include <iostream> using namespace std; class complex { public: complex(){real=0;imag=0;} complex(double r,double i):real(r),imag(i){} complex operator+(complex & c2); void display(); private: double real,imag; }; complex complex::operator+(complex & c2) //运算符重载 { return complex(real+c2.real,imag+c2.imag); } void complex::display() //输出 { cout<<"("<<real<<","<<imag<<")"<<endl; } int main() { complex c2(3.6,4.4),c3; c3=complex(3.5,4.5)+c2; c3.display(); return 0; }
标签:open cte operator close 技术 str ted 形参 turn
原文地址:http://www.cnblogs.com/tinaluo/p/6056807.html