使用类模板需要数组的模板参数列表

Dan*_*Dan 1 c++ templates

我已经在这两天了...

我是 C++ 的初学者,遇到了麻烦。

我只会放置最少量的必要代码。

template <typename Type>
class Array {
        public:

        *//stuff*

        Array operator= (Array const &);
};

template <typename Type>
Array& Array<Type>::operator=(Array const &rhs) {       //ERROR #1 here

*//stuff*

}                                                       //ERROR #2 here
Run Code Online (Sandbox Code Playgroud)

我收到以下 2 个错误

'Array':使用类模板需要模板参数列表
'Array::operator =':无法将函数定义与现有声明匹配

请帮忙。

先感谢您

cdh*_*wie 5

定义的返回类型需要明确拼写为Array<Type> &Array<Type>这是因为编译器在看到 之前并不知道您处于成员定义的上下文中,因此在此之前Array<Type>::您不能在没有模板参数的情况下使用。Array

template <typename Type>
Array<Type>& Array<Type>::operator=(Array const &rhs) {
//   ^^^^^^
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用 C++11 的auto语法来允许使用不带模板参数的名称,因为此语法在编译器知道定义所在的上下文Array指定返回类型。

template <typename Type>
auto Array<Type>::operator=(Array const &rhs) -> Array& {
//                                               ^^^^^^
// This works because the compiler has already encountered "Array<Type>::"
Run Code Online (Sandbox Code Playgroud)