C++ friend function and friend class

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

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


原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 小孩十一个月还没长牙怎么办 吃羊肉上火牙疼怎么办 吃羊肉后上火了怎么办 羊肉吃多了上火怎么办 小孩吃糖牙齿坏怎么办 一岁宝宝吐奶怎么办 一个月宝宝吐奶怎么办 2个月里小孩好哭怎么办 两个月宝宝闹觉怎么办 6岁儿童视力0.5怎么办 单一的三系减少怎么办 血小板低到50该怎么办 放化疗后白细胞低怎么办 化疗后白细胞低发烧怎么办 全程c反应蛋白高怎么办 儿童c反应蛋白高怎么办 c反应蛋白高是怎么办 新生儿c反蛋白高怎么办 c反应蛋白高发烧怎么办 血沉高到50了怎么办啊 血沉和超敏偏高怎么办 孕37周血糖偏高怎么办 孕37周血糖7.0多怎么办 孕妇超敏crp偏高怎么办 高敏c反应蛋白高怎么办 孕17周尿蛋白高怎么办 血小板低到20该怎么办 血象高发烧39度怎么办 新生儿血象3万多怎么办 血象高发烧不退怎么办 半岁宝宝血象高怎么办 5-6小孩免疫力差怎么办 快速c反应蛋白高怎么办 15个月宝宝发烧怎么办 小孩发烧到40度怎么办 孩子发烧到39度怎么办 宝宝抵抗力差总生病怎么办 献血前没休息好怎么办 拔了牙齿一直流血怎么办 拔牙后血块掉了怎么办 生血功能不强怎么办