C++面向对象(六)组合关系中一个类如何访问另一个类的私有成员

//node和link实际上是组合的关系,但是link不能访问node的私有成员
class node
{
public:
	node(int data = 0) :mdata(data), mpnext(NULL){}
private:
	int mdata;
	node *mpnext;
};

class link
{
public:
	link(){ mphead = new node; }
	~link()
	{
		node *pcur = mphead;
		while (pcur != NULL)
		{
			mphead = mphead->mpnext;
			delete mphead;
			pcur = mphead;
		}
	}

	void inserthead(int val)   //头插
	{
		node * ptmp = new node(val);
		ptmp->mpnext = mphead->mpnext;
		mphead->mpnext = ptmp;
	}
	void inserttail(int val)
	{
		node * ptmp = new node(val);//要插入的节点
		node * pcur = mphead;       //用来遍历的指针
		while (pcur->mpnext != NULL) //找到尾节点
		{
			pcur = pcur->mpnext;
		}
		pcur->mpnext = ptmp;       //插入到尾节点后
	} 

	void show()
	{
		node *pcur = mphead->mpnext; //一般头节点不存储有效数据
		while (pcur != NULL)
		{
			cout << pcur->mdata << " ";
		}
		cout << endl;

	}
private:
	node *mphead;
};

我们在link类中访问了node类的私有成员,如mdata 和 mpnext,是不允许的。

解决方案一:将link声明为node的友元类

class node
{
public:
	node(int data = 0) :mdata(data), mpnext(NULL){}
private:
	int mdata;
	node *mpnext;

	friend class link;
};

友元类本质:
C++提高破坏数据封装和隐藏的一种机制,将一个类A声明为另一个类B的友元类,这样B就可以使用A的私有数据。
一般,为了保证数据的完整性,以及数据的封装和隐藏原则,建议不用友元。
友元类的特点:
1.友元是单一的,不能传递

解决方案二:将node类的私有成员公开

//这样外部就可以访问node类的私有成员
class node
{
public:
	node(int data = 0) :mdata(data), mpnext(NULL){}
	int mdata;
	node *mpnext;
};

解决方案三:将node类定义为link类的私有成员变量

class link
{
public:
//这部分代码省略

private:
	class node
	{
	public:
		node(int data = 0) :mdata(data), mpnext(NULL){}
		int mdata;
		node *mpnext;
	};
	node *mphead;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值