5: Hiding the Implementation

1.C++ access control

(1). public

public means all member declarations that follow are available to everyone.

(2) private

The private keyword means that no one can access that member except you, the creator of the type.

(3).protected

This keyword acts just like private, with one exception--inherited.

2. Friends

In C++ ,there is an another keywork named friend which means that a function is not the class's member but it has access to class's private member.

class A
{
private:
	int a;
public:
	A(int m){a = m;};
	int getA();
	friend int fA(A& tmp,int x);
};

int A::getA()
{
	return a;
}

int fA(A& tmp,int x)
{
	return tmp.a = x;
}
In the example, fA() can modify A's private variable a. And also, you can grant access to an another class's function like this:

class A;

class B
{
public:
	void modifyA(A& tmp);
	int test(A& tmp);
};

class A
{
private:
	int a;
public:
	A(int m){a = m;};
	int getA();
	friend void B::modifyA(A& tmp);
};

int A::getA()
{
	return a;
}

void B::modifyA(A& tmp)
{
	tmp.a = 10;
}

int B::test(A& tmp)
{
	//return tmp.a;	//error, a is a private
	return tmp.getA();
}
How to make a class nested automaticaly gave access to private members? To accomplish this, you must follow a particular form: first, declare(without defining) the nested class, then declare it as a friend, and finally define the class.

class A
{
private:
	int a;
public:
	class B;
	friend class B;
	class B{
	public:
		void modifyA(A& tmp);
	};
};

void A::B::modifyA(A& tmp)
{
	tmp.a = 10;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值