4. 输出运算符的重载
本节来讲解如何让 std::out 能够对用户自定义的 Complex 类 的对象进行输出。即可以实现如下代码的功能
Complex c1(1, 2);
std::cout << c1; // 直接输出 c1 对象。
由于做操作数是 std::cout,因此只能使用 友元全局函数的方式重载 << 运算符来实现。
这里 std::cout 是 ostream 类型的对象,并且此运算符重载后需要返回 ostream 对象自身,这个返回的对象供下一个 << 运算进行在进行输出。
示例
重载 << 运算符,实现标准输出。
// filename: std_cout.cpp
#include <iostream>
using namespace std;
class Complex {
public:
Complex(double r=0, double i=0): real(r), image(i){}
Complex operator +(const Complex & right) const {
return Complex (
this->real + right.real,
this->image + right.image);
}
private:
double real;
double image;
// 友元全局函数声明
friend ostream & operator << (ostream & o, const Complex & c);
};
ostream & operator << (ostream & o, const Complex & c) {
o << "(" << c.real << "+" << c.image << "i)";
return o;
}
int main(int argc, char * argv[]) {
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3;
c3 = c1 + c2;
cout << c1 << "+" << c2 << "=" << c3 << endl;
return 0;
}
编译和运行结果如下:
weimz@mzstudio:~$ g++ -o std_cout std_cout.cpp
weimz@mzstudio:~$ ./std_cout
(1+2i)+(3+4i)=(4+6i)