【发布时间】:2016-05-12 15:34:06
【问题描述】:
我有 Node 类,它是 BinaryTree 类的朋友,该类包含 Node 类型的元素。我想制作任何类型的 BinareTree,所以我在两个类上都使用了模板。就像在这段代码中一样:
template <class T>
class Node
{
T value;
Node<T> *left, *right;
friend template <typename T> class BinaryTree; // here is the problem
};
template <class Y>
class BinaryTree{...};
如果我将使用它作为模板,我需要在朋友类 BinaryTree 的声明中使用什么语法? 我的目标是能够写作:
BinareTree<int> tree;
有没有我想到的更好的方法? 谢谢!
【问题讨论】:
-
记住,使用
friend时要问的第一个问题是:你确定要使用friend吗? -
@Kupiakos 注意,虽然有ways to refactor a friend relation,但有时它是有道理的(例如,为了实用主义),如果你知道自己在做什么,只需使用
friend。 -
@Kupiakos 是的,我需要,因为我想访问 BinaryTree 类中 Node 类的私有成员。