c++ 运算符重载

c++ 运算符重载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;
}

 

原文链接: https://www.cnblogs.com/tangcong/archive/2012/03/19/2406064.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    c++ 运算符重载

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/44544

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 下午9:11
下一篇 2023年2月8日 下午9:11

相关推荐