#pragma once
#include <ostream>
#include <iostream>
using namespace std;
class MyComplex {
public:
int GetA() const{
return a;
}
int GetB() const {
return b;
}
//输出重载一
friend ostream& operator < (ostream& out, const MyComplex& com);//注意ostream前不能加const,因为流要插入修改
//输出重载二
ostream& operator > (ostream& out) {
out << "operator>" << a << ", " << b;
return out;
}
static void TestFriend();
private:
int a=0, b=10;
};
//友元函数,是全局函数
ostream& operator < (ostream& out, const MyComplex& com) {
out << "operator<" << com.a << ", " << com.b;
return out;
}
//输出重载三,全局函数
ostream& operator << (ostream& out, const MyComplex& com) {
out << "operator<<" << com.GetA() << ", " << com.GetB();
return out;
}
//测试用例
void MyComplex:: TestFriend() {
MyComplex complex;
//下面2种调用等价
operator <<(std::cout, complex) << endl;
std::cout << complex << std::endl;
//下面2种调用等价
(std::cout < complex) << endl; //加括号因为<<优先级高于<
(operator <(std::cout, complex)) << endl; //友元函数是全局函数
//下面2种调用等价
(complex > std::cout) << endl;
(complex.operator>(std::cout)) << endl;
/*输出结果:
* operator<<0, 10
operator<<0, 10
operator<0, 10
operator<0, 10
operator>0, 10
operator>0, 10
*/
}
|