c++ 运算符重载
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/*
运算符重载,类型转换函数,转换构造函数
无参默认构造函数,带参初始化构造函数,
*/
#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;
}
posted on 2012-03-19 14:41 more think, more gains 阅读(123) 评论(0) 编辑 收藏 举报