运算符重载
两种重载方法
1)成员函数
a + b => a.operator+(b); 一个参数
2)友元函数
a + b => operator+(a, b); 两个参数。
friend 将某个类或函数声明为另一个类的友元,就可以访问另一个类的private成员了。
不能重载运算符:., .*, ::, ?: (共四个)
事例
重载操作符operator<<,因为ostream是系统实现的,不知道其具体实现,
运算符重载中this指针指向运算符左边的对象
所以在非ostream类中实现operator<<重载,应声明为友元函数。
函数声明在类中:
friend ostream & operator<<(ostream &o, const complx &a);
函数实现:
ostream & operator<<(ostream &o, const complx &a) { if(a.img >= 0){ o<<a.real<<"+"<<a.img<<"i"<<endl; } else { o<<a.real<<a.img<<"i"<<endl; } return o; }
友元函数友元类
类的友元函数是定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是成员函数。
友元可以是一个函数,该函数被称为友元函数;友元也可以是一个类,该类被称为友元类,在这种情况下,整个类及其所有成员都是友元。
#include <iostream> using namespace std; class Box { double width; public: friend void printWidth( Box box ); void setWidth( double wid ); }; // 成员函数定义 void Box::setWidth( double wid ) { width = wid; } // 请注意:printWidth() 不是任何类的成员函数 void printWidth( Box box ) { /* 因为 printWidth() 是 Box 的友元,它可以直接访问该类的任何成员 */ cout << "Width of box : " << box.width <<endl; } // 程序的主函数 int main( ) { Box box; // 使用成员函数设置宽度 box.setWidth(10.0); // 使用友元函数输出宽度 printWidth( box ); return 0; }
Width of box : 10
参考:
1. http://www.runoob.com/cplusplus/cpp-friend-functions.html