min*_*box 3 c++ templates arguments
嗨,我仍然想知道为什么我收到此错误消息:
使用类模板'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
Run Code Online (Sandbox Code Playgroud)
CPP文件
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;
}
Run Code Online (Sandbox Code Playgroud)
问题似乎与返回对象的const引用有关.
谢谢.
在编译器看到之前Array<T>::,它不知道您正在定义类模板的成员,因此您不能使用inject-class-name Array作为简写Array<T>.你需要写const Array<T> &.
并且你的赋值运算符中的constness向后倾斜.它应该采用const引用并返回非const引用.