您的位置:首页 > 编程语言 > C语言/C++

C++ friend function and friend class

2017-05-22 15:19 483 查看
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 function
int 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++java