classMyClass { public: MyClass() { regVar = 0; } private: int regVar; //Allow someFunc() to access private member of class MyClass friendvoidsomeFunc(MyClass &obj); //Pass by reference //Note that when passing an object to the function, //we need to pass it by reference //using the & operator. };
//The function someFunc() is defined as a regular function outside the class. //It takes an object of type MyClass as its parameter, //and is able to access the private data members of that object. voidsomeFunc(MyClass &obj){ obj.regVar = 42; cout << obj.regVar; }
intmain(){ MyClass obj; someFunc(obj); }
//Outputs 42
請注意,將Object傳遞給function時,我們需要使用&運算符通過reference將其傳遞(Pass by reference)。因此,我們可以使用實際對象,而不是對象的copy(副本)。 如果不用&的話,我們是Pass by value(通過值傳遞),創建對象的副本。
#include<iostream> usingnamespace std; // forward declaration classB; classA { private: int numA; public: A(): numA(12) { } // friend function declaration friendintadd(A, B); }; classB { private: int numB; public: B(): numB(1) { } // friend function declaration friendintadd(A , B); }; // Function add() is the friend function of classes A and B // that accesses the member variables numA and numB intadd(A objectA, B objectB) { return (objectA.numA + objectB.numB); } intmain() { A objectA; B objectB; cout<<"Sum: "<< add(objectA, objectB); return0;
//Sum: 13 }
Friend Class
您可以定義一個friend class,讓這個friend class access其他class的private member。當一個class成為friend class時,該class的所有member functions都將成為friend functions。
在此示例中,我們有兩個Class - XYZ和ABC。 XYZ Class具有兩個private member ch和num,該類將ABC聲明為friend class。 這意味著ABC可以訪問XYZ的private member ,在ABC class的function disp()access private member num和ch的示例中已經證明了這一點。
#include<iostream> usingnamespace std; classXYZ { private: char ch='A'; int num = 11; public: /* This statement would make class ABC * a friend class of XYZ, this means that * ABC can access the private and protected * members of XYZ class. */ friendclassABC; }; classABC { public: voiddisp(XYZ obj){ cout<<obj.ch<<endl; cout<<obj.num<<endl; } }; intmain(){ ABC obj; XYZ obj2; obj.disp(obj2); return0;
//output : //A //11 }
This
C++中的每個Object都可以通過稱為this pointer來訪問其自己的address(地址)。
在member function中,this指 refer to the invoking object。
classMyClass { public: MyClass(int a) : var(a) { } voidprintInfo(){ //All three alternatives will produce the same result. cout << var<<endl; cout << this->var<<endl; //this is a pointer to the object, so the arrow selection operator is used to select the member variable. cout << (*this).var<<endl; } private: int var; };