运算符重载

来源:互联网 发布:全民奇迹挂机软件 编辑:程序博客网 时间:2024/06/07 23:25
# include <iostream># include <math.h># include <stdio.h>using namespace std;class complex{public:complex(double r = 0.1, double i = 0.2) {real = r; imag = i;}complex operator+ (complex c2); //+重载为成员函数complex operator- (complex c2); //-重载为成员函数void display(); //输出负数private:double real;double imag;};complex complex::operator +(complex c2)  //重载函数实现{complex c;c.real = c2.real+real;c.imag = c2.imag+imag;return complex(c.real, c.imag);}complex complex::operator -(complex c2)   //重载函数实现{complex c;c.real = c2.real-real;c.imag = c2.imag-imag;return complex(c.real, c.imag);}void complex::display(){cout << "(" << real << "," << imag << ")" << endl;}int main(void){complex c1(5,4), c2(2,10), c3;cout << "c1 = ";c1.display();cout << "c2 = ";c2.display();c3 = c1 - c2;  //c3 = c1.operat1-c2cout << "c3 = c1 - c2";c3.display();c3 = c1 + c2;cout << "c3 = c1 + c2";c3.display();return 0;}

c1 = (5,4)
c2 = (2,10)
c3 = c1 - c2(-3,6)
c3 = c1 + c2(7,14)
0 0
原创粉丝点击