您的位置:首页 > 其它

????friend关键字

2016-03-24 13:35 267 查看
#include "stdafx.h"
#include <iostream>
using namespace std;

//A里面有个private的变量,需要被其他的如
//全局函数g(A *a)、h()、结构体C、结构体中的某个函数B::f(A *a)访问

struct A;

struct B{
void f(A *a);        //这里用到了A,那么前面必须前面有A的声明
};

struct A{
private:
int i;
public:
void ini();
friend void g(A *a);        //在这里声明也是算数的,算是全局的声明,因此g和h可以写在下面
friend void h();
friend struct C;            //这个表明在C的任何一个函数内都可以访问到
friend void B::f(A *a);        //这里必须事先有该函数声明才行,因此B的结构体定义前移
};

void B::f(A *a){
cout<<"B::f gets the value: "<<a->i<<endl;
}

void A::ini(){
i=20;
}

void g(A *a){
cout<<"g gets the value: "<<a->i<<endl;
}

void h(){
A a;
a.i=10;
cout<<"can new an A in h:  "<<a.i<<endl;
}

struct C{

};

int _tmain(int argc, _TCHAR* argv[])
{

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: