[英]How do I write a member function that returns a type that only exists in the class?
I'm actually implementing a doubly-linked list in C++. 我实际上是在C ++中实现一个双向链接列表。
Here's a MWE of sorts: 这是各种MWE:
namespace mynamespace {
template <typename T>
class List {
public:
List();
void prepend(T);
void append(T);
void remove(T);
private:
struct Node {
T value_;
Node * prev_;
Node * next_;
};
private:
Node * find(T); // <-- THIS IS MY PROBLEM
private:
Node * head_;
Node * tail_;
};
}
The reason I'd like to create that function is because I figured it'd be handy if I could traverse the list with a function like that until I find a given element (I'll need to do the same with the remove()
function anyways) 我想创建该函数的原因是因为我认为,如果可以使用这样的函数遍历列表,直到找到给定的元素,这将非常方便(我需要对
remove()
相同的操作仍然起作用)
But how do I define that function outside the class
definition? 但是,如何在
class
定义之外定义该函数?
Since Node
is a private member of the List
class, this is not working: 由于
Node
是List
类的私有成员,因此无法正常工作:
template <typename T>
Node * List<T>::find(T val)
{
// stuff
}
I suppose defining the function inside the class
definition would work, because Node
makes sense there... Would that be the proper way? 我想定义的内部函数
class
的定义会的工作,因为Node
有意义那里...那是要正确的方法是什么? Even if so, I suppose there must be a way to define the function the way I'm trying to... 即使这样,我想也必须有一种方法可以定义我要尝试的功能...
Since
Node
is a private member of theList
class, this is not working:由于
Node
是List
类的私有成员,因此无法正常工作:
Actually, that's not correct. 实际上,这是不正确的。 It's not failing because
Node
is private, but because Node
is nested inside of List
. 这样做不是因为
Node
是私有的,而是因为Node
嵌套在List
。 The name of the Node
class isn't Node
, it's List<T>::Node
. Node
类的名称不是Node
,而是List<T>::Node
。 However, since Node
depends on T
, you have to write typename List<T>::Node
, otherwise the compiler assumes that List<T>::Node
is a value rather than a type. 但是,由于
Node
依赖于T
,因此您必须编写typename List<T>::Node
,否则编译器会假定List<T>::Node
是值而不是类型。 See this question for more information. 有关更多信息,请参见此问题 。
In short, replace this: 简而言之,替换为:
template <typename T> Node * List<T>::find(T val)
With this: 有了这个:
template <typename T>
typename List<T>::Node * List<T>::find(T val)
Alternatively, as StoryTeller noted, if you are in the context of the List<T>
class, you can just use Node
. 另外,如StoryTeller所述,如果您位于
List<T>
类的上下文中,则可以仅使用Node
。 You can get in this context by using a trailing return type: 您可以通过使用尾随返回类型来获得此上下文:
template <typename T>
auto List<T>::find(T val) -> Node *
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.