這個函式的prototype需要寫在class裡面,且在前面加上friend的修飾詞,如:
friend void setValue( MyClass &, int );該prototype可以放在class裡的任何一處,他與private/public無關,不會影響,但是建議放在最前面會是比較清楚的方法。
friend function有個物件的參數,所以我們才知道要針對的是哪個class instance。
myClass.h
class MyClass{ friend void setDoctor(MyClass &, int); public: //constructor MyClass(int = -1); void displayHowManyDoctor(); private: int doctor; };
myClass.cpp
#include <iostream> #include "myClass.h" using namespace std; MyClass::MyClass(int doctor){ this->doctor = doctor; } void MyClass::displayHowManyDoctor(){ cout << "The Number of Doctor is " << this->doctor << endl; } // friend function void setDoctor(MyClass &myClass, int new_doctor){ cout << "grabbing private variable >> " << myClass.doctor << endl; myClass.doctor = new_doctor; }
main.cpp
#include <iostream> #include "myClass.h" using namespace std; int main(){ // define an apple instance MyClass apple; // set the doctor value by using friend function setDoctor(apple, 1); // print out apple.displayHowManyDoctor(); return 0; }
No comments:
Post a Comment