類的友元函數是定義在類外部,但有權訪問類的所有私有成員和保護成員。盡管友元函數的原型有在類的定義中出現過,但友元函數并不是成員函數。
友元可以是一個函數,該函數被稱為友元函數;友元也可以是一個類,該類被稱為友元類。在這種情況下,整個類及其所有成員都是友元。如果要聲明函數為一個類的友元,需要在類定義中該函數原型前使用關鍵字friend,如下所示:
class Box {double width; public:double length;friend void printWidth(Box box);void setWidth(double wid); };
聲明類ClassTwo的所有成員函數作為類的ClassOne的友元,需要在類ClassOne的定義中放置如下聲明:
friend class ClassTwo;
/*** friend.cpp ***/ #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; }void printWidth(Box box) {cout << "Width of box : " << box.width << endl; }int main() {Box box;box.setWidth(10.0);printWidth(box);return 0; }
運行結果:
exbot@ubuntu:~/wangqinghe/C++/20190807$ ./friend
Width of box : 10
因為友元函數沒有this指針,則參數要有三種情況:
- 要訪問非static成員時,需要對象作為參數;
- 要訪問static成員或者全局變量時,不需要對象作為參數;
- 如果做參數的對象是全局對象,則不需要對象做參數。
友元類的使用
/*** classfriend.cpp ***/ #include<iostream> using namespace std;class Box {double width; public:friend void printWidth(Box box);friend class BigBox;void setWidth(double wid); };class BigBox { public:void Print(int width, Box &box){box.setWidth(width);cout << "Width of box: " << box.width << endl;} };void Box::setWidth(double wid) {width = wid; }void printWidth(Box box) {cout << "Width of box : " << box.width << endl; }int main() {Box box;BigBox big;box.setWidth(10.0);printWidth(box);big.Print(20,box);return 0; }
運行結果:
exbot@ubuntu:~/wangqinghe/C++/20190807$ ./classfriend
Width of box : 10
Width of box: 20