friend

来源:互联网 发布:淘宝耳环店铺 编辑:程序博客网 时间:2024/06/11 19:19
友元机制允许一个类将对其非公有成员的访问权授予指定的函数或类。友元的声明以关键字 friend 开始。它只能出现在类定义的内部。友元声明可以出现在类中的任何地方:友元不是授予友元关系的那个类的成员,所以它们不受声明出现部分的访问控制影响


友元可以是普通的非成员函数, 或前面定义的其他类的成员函数, 或整个类。将一个类设为友元, 友元类的所有成员函数都可以访问授予友元关系的那个类的非公有成员.


1.友元可以是普通的非成员函数,可以访问授予友元关系的那个类的私有成员
#include "stdafx.h"
#include <iostream>
using namespace std;


class MyClass
{
public:
MyClass(int a){iNumber = a;}
friend void Out();
private:
int iNumber;
};


void Out()
{
MyClass mc(1);
cout<<mc.iNumber<<endl;
}


void _tmain(int argc, _TCHAR* argv[])
{
Out();
}




2.友元可以是普通的非成员函数,可以访问授予友元关系的那个类的私有静态常量成员
#include "stdafx.h"
#include <iostream>
using namespace std;


class MyClass
{
public:
friend void Out();
private:
const static int iNumber = 10;
};


void Out()
{
MyClass mc;
cout<<mc.iNumber<<endl;
}


void _tmain(int argc, _TCHAR* argv[])
{
Out();
}


3.将一个类设为友元, 友元类的所有成员函数都可以访问授予友元关系的那个类的非公有成员.
#include "stdafx.h"
#include <iostream>
using namespace std;


class MyClass
{
public:
friend class My;
private:
const static int iNumber = 10;
};


class My{
public:
void Get();
};


void My::Get()
{
MyClass mc;
cout<<mc.iNumber<<endl;
}


void _tmain(int argc, _TCHAR* argv[])
{
My my;
my.Get();
}


4.友元可以是其他类的成员函数
#include "stdafx.h"
#include <iostream>
using namespace std;


class My{
public:
void Get();
};


class MyClass
{
public:
const static int iData = 10;
friend void My::Get();


private:
const static int iNumber = 10;
};


void My::Get()
{
MyClass mc;
//cout<<mc.iNumber<<endl; //不可以访问MyClass的私有成员
cout<<mc.iData<<endl;//可以访问公有成员
}


void _tmain(int argc, _TCHAR* argv[])
{
My my;
my.Get();
}
0 0
原创粉丝点击