C++ friend function and friend class

来源:互联网 发布:冯满天知乎 编辑:程序博客网 时间:2024/06/03 01:38

Friends are not member functions. a friend function of a class is defined outside that class but it has the right to access all private and protected members of the class.Even though the prototype for friend functions appear in the class definition,friends are not member functions.

a friend can be a function,template function ,or member function,or a class or class template,in which case the entire class and all of its members are friends.

To declare a function as a friend of a class, precede the prototype in the class definition with keyword friend as follows:

class A{       int x;public:       friend int getsValue(A& a);};// friend functionint getsValue(A &a){return a.x;}
To declare all members of the class ClassOne as friends of  class ClassOne ,place a following declaration in the definition of the ClassOne.

friend class ClassOne;
consider the following program:

#include<iostream>using namespace std;class Test{public:Test(int a):x(a){};friend int getsValue(Test &classA);private:int x;};int getsValue(Test &classA){return classA.x;}int main(int argc,char *argv[]){Test A(10);cout<<"value in class Test is : "<<getsValue(A)<<endl;return 0;}
when the above code is complied and excuted ,it produces the following result:


value in class Test is : 10


原创粉丝点击