<code>
#ifndef VECTOR_H
#define VECTOR_H
template <class T>
class Vector
{
public:
Vector();
~Vector();
void add(T element);
int size() const;
T get(int i) const;
void set(int i, T element);
bool contains(T element);
Vector<T>& operator=(const Vector<T> &rhs);
private:
int numElements;
int capacity;
T *elements;
void expand();
};
template <class T>
Vector<T>::Vector()
{
numElements = 0;
capacity = 10;
elements = new T[capacity];
}
template <class T>
Vector<T>::~Vector()
{
delete[] elements;
}
template <class T>
void Vector<T>::add(T element)
{
if (numElements >= capacity)
{
expand();
}
elements[numElements] = element;
numElements++;
}
template <class T>
int Vector<T>::size() const
{
return numElements;
}
template <class T>
T Vector<T>::get(int i) const
{
return elements[i];
}
template <class T>
void Vector<T>::set(int i, T element)
{
elements[i] = element;
}
template <class T>
void Vector<T>::expand()
{
T *tempElements = new T[capacity * 2];
for (int i = 0; i < capacity; i++)
{
tempElements[i] = elements[i];
}
delete[] elements;
elements = tempElements;
capacity *= 2;
}
template <class T>
bool Vector<T>::contains(T element)
{
for (int i = 0; i < numElements; i++)
{
if (elements[i] == element)
{
return true;
}
}
return false;
}
template <class T>
Vector<T>& Vector<T>::operator=(const Vector<T> &rhs)
{
delete[] elements;
numElements = rhs.size();
capacity = numElements * 2;
elements = new T[capacity];
for(int i = 0; i < numElements; i++)
elements[i] = rhs.get(i);
}
#endif
</code>
我对C ++很陌生,并且有关于数据结构和抽象的任务。我在分配中得到了一些CPP和头文件,除了这个之外它工作正常。当我编译时,它说&#34;严重程度代码描述项目文件行抑制状态 错误C4716&#39; Vector :: operator =&#39;:必须返回值&#34;
答案 0 :(得分:1)
Vector<T>::operator=()
不会在任何地方返回,而且必须。
这允许这样的语法:
a = b = c;
所以只需加上
return (*this);
在方法结束时。