友元函数和成员函数选择的方法
- 当无法修改左操作数的类时,使用全局函数进行重载
- =, [], ()和->操作符只能通过成员函数进行重载
重载左移操作符
#include <iostream>
using namespace std;
class Complex
{
friend void operator<< (ostream &out, const Complex &c);
public:
Complex()
{
a = 0;
b = 0;
}
Complex(int a, int b)
{
this->a = a;
this->b = b;
}
void print()
{
printf ("%d + %di\n", a, b);
}
Complex operator+(const Complex &c2) const
{
Complex tmp(a+c2.a, b+c2.b);
return tmp;
}
private:
int a; // 实部
int b; // 虚部
};
ostream& operator<< (ostream &out, const Complex &c)
{
out << c.a << " + " << c.b << "i";
return out;
}
int main()
{
Complex c1(1,2 );
c1.print();
// << 是一个操作符 我们可以重载它的功能
// cout 是一个对象 cout 是 ostream 的一个对象
// operator<< (cout, c1)
// operator<< (ostream &out, const Complex &c);
// 1、 operator<< (cout, c1) << endl
// 2、operator<< (operator<< (cout, c1), endl)
// 3、operator<< (cout, endl)
cout << c1 << endl;
// 全局 ---> 内部
// operator<< (ostream &out, int a) -----> operator<< (int a)
// Complex * const this ostream *const this
// 左移和右移操作只能用友元函数进行重载,写成全局函数,无法写成内部函数,因为无法修改 ostream 类
return 0;
}
执行结果:
1 + 2i
1 + 2i
类成员函数无法完成左移操作符的重载
因为拿不到cout这个类的源码
cout.operator<<(c1);
友元函数重载注意点
在第一个参数需要隐式转换的情形下,使用友员函数重载运算符是正确的选择 友员函数没有 this指针,所需操作数都必须在参数表显式声明,很容易实现类型的隐式转换
C++中不能用友员函数重载的运算符有:
= () [] ->