您的位置:首页 > 编程语言 > C语言/C++

c++重载>>与<<

2016-07-22 11:33 393 查看
输入和输出运算符只能用友元函数重载。

友元函数:指某些虽然不是类成员却能够访问类的所有成员的函数。

#include <iostream>

using namespace std;

class complex{
private:
double re, im;
public:
complex(double re, double im){
this->re = re;
this->im = im;
}
complex(){
this->re = 0;
this->im = 0;
}
complex operator !();
complex operator +(const complex& obj);
friend ostream& operator << (ostream& os, complex c);
friend istream& operator >> (istream& is, complex& c);
complex& operator++(){
this->re += 1;
this->im += 1;
}
const complex operator++(int){
complex old;
old.re = this->re;
old.im = this->im;
++(*this);
return old;
}
void operator+=(const complex temp){
this->re += temp.re;
this->im += temp.im;
}
};
complex complex::operator +(const complex& obj){
complex temp;
temp.re = obj.re + this->re;
temp.im = obj.im + this->im;
return temp;
}
complex complex::operator !(){
complex temp;
temp.re = -this->re;
temp.im = -this->im;
return temp;
}
ostream& operator<<(ostream& os, complex c){
os<<c.re;
if(c.im>0)
os<<"+"<<c.im<<"i"<<endl;
else
os<<c.im<<"i"<<endl;
return os;
}
istream& operator >> (istream& is, complex& c){
is>>c.re>>c.im;
return is;
}
int main(){
complex obj(1,2),obj1(3,-4);
obj += obj1;
cout<<obj;
cout<<obj1;
cin >> obj;
cout << obj++ <<std::endl;
cout << obj;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: