C++笔记之 运算符重载
//格式
//函数类型 operator 运算符(形参表)
//{
// 函数体;
//}
#include<iostream>
using namespace std;
class Complex{
public :
double m_real;
double m_imag;
Complex ()
{}
Complex (double m_real,double m_imag)
{
this->m_imag=m_imag;
this->m_real=m_real;
}
void show()
{
cout<< m_real <<"+"<<m_imag<<"i" <<endl;
}
Complex operator-(Complex &c)
//&表示引用
//给一个变量起别名
//使用引用可以减少内存的消耗和赋值的过程
{
return Complex (this->m_real-c.m_real,this->m_imag- c.m_imag);
}
};
//cout<<a<<b
//1.cout = cout.operator(a)
//2.cout = cout.operator(b)
//保证所有的cout为同一对象
//入参又采用引用 保证是cout全局变量的别名
//返回值依旧使用引用 保证等的左侧依旧是原本cout 不发生改变
ostream& operator<<(ostream &out,Complex &c)// ***输出流的重载***
{
out<< c.m_real << "+" << c.m_imag <<"i" <<endl;
return out;
};
istream& operator>>(istream &in,Complex &c)//**输入流的重载**
{
in>> c.m_real >> c.m_imag;
return in;
};
int main()
{
Complex c1(10.0,5.0);
Complex c2(5.0,10.0);
Complex c3;
cin >>c3;
//Complex c3 = c1 + c2;//c1 + c2 相当于调用
//c1为this 所指向的对象
//c2位传入的参数
//Complex c3=c1-c2;
c3.show();
//cout<<c1<<c2;
return 0;
}
//可以用作重载的运算符:
//算术运算符:+,-,*,/,%,++,--;
//位操作运算符:&,|,~,^,<<,>>
//逻辑运算符:!,&&,||;
//比较运算符:<,>,>=,<=,==,!=;
//赋值运算符:=,+=,-=,*=,/=,%=,&=,|=,^=,<<=,>>=;
//其他运算符:[],(),->,,(逗号运算符),new,delete,new[],delete[],->*。
//下列运算符不允许重载:
//. .* :: ?: