【问题标题】:Class templates and friend Classes类模板和朋友类
【发布时间】: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 类的私有成员。

标签: c++ templates friend


【解决方案1】:

如果您查找 template friends 的语法,您会找到正确的方法:

class A {
    template<typename T>
    friend class B; // every B<T> is a friend of A

    template<typename T>
    friend void f(T) {} // every f<T> is a friend of A
};

虽然你可能只是想加好友:

friend class BinaryTree<T>;

【讨论】:

猜你喜欢
  • 2011-03-18
  • 1970-01-01
  • 2016-10-29
  • 1970-01-01
  • 2011-10-14
  • 1970-01-01
  • 2014-10-03
  • 1970-01-01
  • 2012-01-21
相关资源
最近更新 更多