使用类模板需要模板参数。

3

你好,我仍然在想为什么会得到以下错误信息:

使用类模板“Array”需要模板参数。

头文件:

#ifndef Array_h
#define Array_h


template< typename T>
class Array
{
public:
    Array(int = 5);
    Array( const Array &);

    const Array &operator=(Array &);
    T &operator[](int);
    T operator[](int) const;

    // getters and setters
    int getSize() const;
    void setSize(int);

    ~Array();

private:
    int size;
    T *ptr;

    bool checkRange(int);


};

#endif

C++文件

template< typename T >
const Array &Array< T >::operator=(Array &other)
{
    if( &other != this)
    {
        if( other.getSize != this->size)
        {
            delete [] ptr;
            size = other.getSize;
            ptr = new T[size];
        }

        for ( int i = 0; i < size; i++)
        {
            ptr[i] = other[i];
        }
    }
    return *this;
}

问题似乎出在返回对象的const引用上。谢谢。
1个回答

6

在编译器看到 Array<T>:: 之前,它并不知道你正在定义类模板的成员函数,因此你不能使用内嵌类名 Array 作为 Array<T> 的缩写。你需要写成 const Array<T> &

你在赋值运算符中弄反了 const 属性。它应该接受一个 const 引用并返回一个非 const 引用。

此外,为什么模板只能在头文件中实现?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接