[英]How do I declare a template instantiation as a friend of my class?
My node
class needs the corresponding linked
class to be a friend. 我的node
类需要相应的linked
类成为朋友。 I wrote it as 我写成
template <typename T>
class node{
T value;
node<T> *next;
friend class linked<T>;
};
template <typename T>
class linked{
linked();
~linked();
node<T> *head;
};
I get a compilation error complaining that linked
is not a class template. 我收到编译错误,抱怨linked
不是类模板。 How can I declare linked<T>
to be a friend of node<T>
? 我如何才能声明linked<T>
为node<T>
的朋友?
If you want to make the instantiation of linked
with the same template parameter T
to be the friend, you need to forward declare class template linked
at first. 如果要使具有相同模板参数T
的linked
实例化为好友,则需要先声明linked
类模板。
// forward declaration
template <typename T>
class linked;
template <typename T>
class node {
...
friend class linked<T>;
// or since C++11 you can
friend linked<T>;
};
template <typename T>
class linked {
...
};
You have to declare the class linked as follows ahead of using it in Node class. 您必须在Node类中使用它之前声明链接的类,如下所示。 But your code looks more messy than just this issue. 但是您的代码看起来不仅仅只是这个问题。 And I am not sure what you are actually attempting. 而且我不确定您实际上在尝试什么。
template <typename T>
class linked;
template <typename T>
class node{
private:
T value;
node<T> *next;
friend class linked<T>;
};
The error is that where the statement friend class linked<T>;
错误是语句中的friend class linked<T>;
appears, the linked
class has not been declared. 出现时,尚未声明linked
类。 Add the following before class node
. 在class node
之前添加以下内容。
template <typename T>
class linked;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.