c++通过定义虚数类实现加号、左右移等操作运算符的重载,可cout、cin虚数

版权声明: https://blog.csdn.net/hiudawn/article/details/79953020
#include<iostream>
using namespace std;

class Complex
{
public:
//无参构造
Complex()
{
this->r = 0;
this->v = 0;
}
//有参构造
Complex(int r,int v)
{
this->r = r;
this->v = v;
}
//打印值
void print()
{
if(v>0)
{
cout<<r<<"+"<<v<<"i"<<endl;
}
else
{
cout<<r<<"-"<<v<<"i"<<endl;
}
}
//调用成员函数的相加方法,也是一种常规的办法
Complex add(Complex another)
{
Complex temp(this->r+another.r,this->v+another.v);
return temp;
}
//都是加号的重载,减号一个道理
//+号运算符的重载,创建一个临时变量返回,避免覆盖某一个对象
Complex operator+(Complex another)
{
Complex temp(this->r+another.r,this->v+another.v);
return temp;
}
//+=操作运算符的重载,返回的对象仍然是自己
Complex& operator+=(Complex another)
{
this->r += another.r;
this->v += another.v;
return *this;//因为this是指针,*this就是当前对象
}
//++操作运算符重载,返回的对象仍然是自己,并且可以可以写成++++a
Complex& operator++()//形如++a
{
this->r++;
this->v++;
return *this;
}
//++操作运算符重载,返回的对象仍然是自己,但不能写成a++++
const Complex& operator++(int)//形如a++
{
//这里的int只是哑元参数,并没作用,但没这个就不能实现后置++重载
++this->r;
++this->v;
return *this;
}
//==的重载,返回一个tag
bool operator==(Complex another)
{
if(this->r==another.r&&this->v==another.v)
{
return true;
}
else
{
return false;
}
}
//<<和>>的重载,即用cout、cin输出输入Complex
friend ostream& operator<<(ostream& os,Complex c);
friend istream& operator>>(istream& is,Complex &c);

private:
//实部和虚部
int r;
int v;
};
//cout最好写在外面,不然调用的时候会变成 c << cout;非常奇怪。
//cout是一个ostream对象,而且支持多<<
ostream& operator<<(ostream& os,Complex c)
{
if(c.v>0)
{
cout<<c.r<<"+"<<c.v<<"i";
}
else
{
cout<<c.r<<"-"<<c.v<<"i";
}
return os;
}
//cin的重载
istream& operator>>(istream& is,Complex &c)
{
cout<<"实部:"<<endl;
int r;int v;
cin>>r;
cout<<"虚部:"<<endl;
cin>>v;
c.r = r;
c.v = v;
return is;
}



int main(void)
{
Complex a(1,1);
Complex b(2,2);
//Complex c = a.add(b);//常规方法
Complex c = a+b+b;
c.print();
cout<<"---"<<endl;
a.print();
//三种+1方法
a += a;
a++;
++a;
//(a+=b)+=b;//这个也能运算
a.print();
cout<<a<<endl;
//==操作符
cout<<(a==b)<<endl;
cout<<(a==a)<<endl;
//cin测试
Complex cc;
cin>>cc;
cout<<"cc= "<<cc<<endl;
return 0;
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页