在C++中, 重载 << 只能使用全局函数,下面代码是具体实现。
#include<iostream>
using namespace std;
class Complex {
private:
int a;
int b;
// friend void operator<<(ostream& out, Complex& c1);
friend ostream& operator<<(ostream& out, Complex& c1);
public:
Complex(int a, int b) {
this->a = a;
this->b = b;
}
};
//void operator<<(ostream& out, Complex& c1) {
// out << c1.a << " + " << c1.b << "i" << endl;
//}
ostream& operator<<(ostream& out, Complex& c1) {
out << c1.a << " + " << c1.b << "i" << endl;
return out;
}
int main() {
Complex c1(1, 2), c2(3, 4);
cout << c1; //重载<<操作符
cout << c1 << c2 << endl;
system("pause");
}

C++重载<<运算符
425

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



