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;
};

猜你喜欢

转载自blog.csdn.net/KingOfMyHeart/article/details/90105495