考虑下面的例子:
template <typename T>
class Vector {
T* data;
public:
class Iterator {
T* i;
public:
Iterator& operator++();
};
};
如果我想实现“operator++”函数,我会这样写:
template <typename T>
Vector<T>::Iterator& Vector<T>::Iterator::operator++() {
i++;
return *this;
}
但随后我收到了这些错误行:
error C2143: syntax error : missing ';' before '&'
error C2065: 'T' : undeclared identifier
error C2923: 'Vector' : 'T' is not a valid template type argument for parameter 'T'
为什么会这样?我应该怎么做才能解决这个问题?
非常感谢。
最佳答案
编译器不知道Vector
的成员Iterator
一定是类型,所以需要用typename
来告诉它关键词:
template <typename T>
typename Vector<T>::Iterator& Vector<T>::Iterator::operator++() {
//here^
i++;
return *this;
}
参见 this question有关 typename
的更多详细信息。
关于c++ - 如何实现模板内部类函数(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30752129/