什麼時候在 C++ 中使用 'friend'?
類的友元函式在該類的作用域之外定義,但它有權訪問該類的所有私有和受保護的成員。即使友元函式的原型出現在類定義中,友元也不是成員函式。
友元可以是函式、函式模板或成員函式,也可以是類或類模板,在這種情況下,整個類及其所有成員都是友元。
要將函式宣告為類的友元,請在類定義中使用關鍵字 friend 來表示函式原型,如下所示 -
class Box {
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};要將 ClassTwo 類的所有成員函式宣告為 ClassOne 類的友元,請在 ClassOne 類的定義中放置以下宣告
示例
friend class ClassTwo;
For example,
#include <iostream>
using namespace std;
class Box {
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
// Member function definition
void Box::setWidth( double wid ) {
width = wid;
}
// Note: printWidth() is not a member function of any class.
void printWidth( Box box ) {
/* Because printWidth() is a friend of Box, it can
directly access any member of this class */
cout << "Width of box : " << box.width <<endl;
}
// Main function for the program
int main() {
Box box;
// set box width without member function
box.setWidth(10.0);
// Use friend function to print the wdith.
printWidth( box );
return 0;
}輸出
這將產生如下輸出 -
Width of box: 10
即使函式不是類的成員,它也可以直接訪問該類的成員變數。這在某些情況下非常有用。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP