现在的位置: 首页 > 综合 > 正文

c++ 运算符重载

2012年11月13日 ⁄ 综合 ⁄ 共 707字 ⁄ 字号 评论关闭
View Code

/*
运算符重载,类型转换函数,转换构造函数
无参默认构造函数,带参初始化构造函数,
*/
#include <iostream.h>
//#include <iostream>
#include <cstdlib>
//using namespace std;
class Complex
{
public:
Complex( ) { real = 0; imag = 0; } //无参默认构造函数
//Complex(double r) { real = r; imag = 0;} 转换构造函数
Complex(double r, double i) { real = r; imag = i;} //带参构造函数
operator double( ) { cout<<"real = "<<real;return real;} //类型转换函数
friend Complex operator +(Complex c1, Complex c2); //运算符重载
void display( );
private:
double real;
double imag;
};

Complex operator +(Complex c1, Complex c2)
{
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}

void Complex::display( )
{
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}

int main( )
{
Complex c1(3,4), c2(5,-10), c3;
double t = c1 + 2.5;
cout<<"t = "<<t<<endl;
c3.display( );
c3 = c1 + c2;
c3.display();
system("pause");
return 0;
}

 

抱歉!评论已关闭.