何時在 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