重载运算符 << 和 >>
- 只能重载为全局函数
- cout 是 ostream 类的对象,cin 是 istream 类的对象,要想达到这个目标,就必须以全局函数(友元函数)的形式重载<<和>>
- 否则就要修改标准库中的类,这显然不是我们所期望的
代码测试效果
#include <iostream>
#include <iomanip>
using namespace std;
class Complex
{
private:
double m_a, m_b;
public:
//以全局函数的形式进行重载
friend Complex operator+(const Complex &a, const Complex &b);
//以全局函数重载>> 和 <<
friend istream & operator >> (istream & in, Complex & a);
friend ostream & operator << (ostream & out, const Complex & b);
void show()
{
cout << this->m_a << " " << this->m_b << endl;
}
public:
Complex(double a, double b) : m_a(a),m_b(b){}
Complex(){}
};
Complex operator+(const Complex &a, const Complex &b)
{
return Complex(a.m_a+b.m_a, a.m_b + b.m_b);
}
istream & operator >> (istream & in, Complex & a)
{
in >> a.m_a >> a.m_b;
return in; // 返回 istream ,方便连续使用
}
ostream & operator << (ostream &out, const Complex &b)
{
out << b.m_a << " " << b.m_b;
return out;
}
int main()
{
Complex a,b,c;
cin >> a >> b;
c = a + b;
cout << c << endl;
return 0;
}
- 为了连续输入和输出, 函数均采用输入输出流引用操作
- 函数的返回值类型为ostrem,第一个参数也是一样的ostream
- cout 是 ostream 类的对象,cin 是 istream 类的对象
- operator<<(cin , c);
参考:
- http://c.biancheng.net/cpp/biancheng/view/3016.html
本文介绍如何以全局函数形式重载运算符<<和>>,以实现自定义类对象的输入输出。通过具体示例代码展示了重载过程,并解释了为何需要这样重载。
575

被折叠的 条评论
为什么被折叠?



