本文介绍了链接列表中的朋友类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是朋友类以及如何在链接列表中使用它?
我在Google上进行了搜索,但希望听取专家的意见.

what is friend class and how it is used in linklist?
i have searched on google but want to listen from experts

推荐答案

class A {
	private:
		int a;
	friend class B; //This lets any code in class B access anything private in here
};

class B {
	public:
		void GetA(const A &object) {
			return object.a; //This would usually be illegal because A.a is private, but this class is a friend of A, so it is allowed
		}
};



但是,在链接列表中,不需要这样做.
链表中的每个节点通常都属于同一类.



In a linked list however, this should not be needed.
Each node in a linked list would typically all be of the same class.


成员8370427写道:
Member 8370427 wrote:

您在最后两行所说的话.您能再解释一下吗?

what you said in last two lines.can you explain it more


参见 Wikipedia [ ^ ]以获取链表的图形示例.

在代码中,这看起来像:


See Wikipedia[^]for a graphic example of a linked list.

In code, this would look like:

template<typename t>
class LinkedListNode {
	public:
		LinkedListNode() : m_pNext(NULL) { }
		LinkedListNode(T tData) : m_pNext(NULL), m_tData(tData) { }
		void SetNext(LinkedListNode *node) { m_pNext = next; }
		LinkedListNode *GetNext() { return m_pNext; }
		void SetData(T &tData) { m_tData = tData; };
		T &GetData() { return m_tData; };

	private:
		LinkedListNode *m_pNext;
		T m_tData;
};



这是一个非常基本的单链表.本示例适用于整数链接列表:



This is a very basic single linked list. This example is for a linked list of integers:

LinkedListNode<int> head = new LinkedListNode<int>(3);
LinkedListNode<int> next = new LinkedListNode<int>(1);
head->SetNext(next);
next->SetNext(new LinkedListNode<int>(2));
//Now print our elements
LinkedListNode<int> node = head;
while (node != NULL) {
	printf("%d\n", node->GetData());
	node = node->GetNext();
}



这样就给出了链表3-> 1-> 2(每个数字将被打印在输出中的单独一行上)

您将为诸如add to end之类的功能添加更多功能,这些功能将一直循环直到找到GetNext()NULL的节点,然后将其设置在新节点旁边.

这里的重点是链接列表的每个部分都属于同一类LinkedListNode.

如果您仍需要帮助来了解链接列表,请 google [ ^ ]是你的朋友.



This gives the linked list 3->1->2 (each number would be printed on a separate line in the output)

You would add more functionality for things like add to end, which would loop through until it finds the node which has a GetNext() of NULL, and then set that next to the new node.

The point here is that every part of the linked list is of the same class, LinkedListNode.

If you still need help understanding linked lists, google[^] is your friend.


这篇关于链接列表中的朋友类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 09:46