模板化 C++ class 有一个 'expected unqualified-id'
Templated C++ class has an 'expected unqualified-id'
对于 class 作业,我们必须在模板化的 .h 文件中编写 STL 向量。我尝试 运行 这个和我的所有成员函数都可以工作,除了赋值错误的重载。它位于最底部,是倒数第二个成员函数。
当给我分配任务时,我被要求超载 Vector<T>& operator=(const Vector&v)
template <class T>
class Vector{
private:
int current_size, capacity;
T* arr;
public:
Vector();
~Vector();
unsigned int size();
void grow(); //where does this belong?
void push_back(const T& elt);
void pop_back();
T& at(int pos);
T& front();
T& back();
bool empty();
void insert (const T&elt, int pos);
void erase(int pos);
Vector<T>& operator=(const Vector& v);
T& operator[](int n);
};
template <class T>
Vector<T>& Vector<T>::operator=(const Vector& v){
current_size= v.size();
capacity= v.capacity();
}
错误是"expected unqualified id"错误的行是:
"Vector& Vector::operator=(const Vector& v)"{
这段代码有很多很多问题。
Zeroth,你的缩进风格让代码很难阅读。每次打开新范围时,缩进!
首先,定义成员函数:
template <class T>
typename Vector<T>::T& at(int pos)
template <class T>
Vector<T>:: T& back()
正确的语法是return-type class-name::member-name
。所以这些应该是:
template <class T>
T& Vector<T>::at(int pos)
template <class T>
T& Vector<T>::back()
其次,delete
-ing。 arr
是 T
的动态数组。只有它是动态的。您在多个地方试图删除单个元素:
delete arr[current_size-1];
这是一个无效的操作。
第三,针对你的具体问题,参数v
是const
:
template <class T>
Vector<T>& Vector<T>::operator=(const Vector<T>& v){
这意味着您只能调用 const
限定的成员函数。 size()
不符合 const
条件。您必须添加:
unsigned int size() const;
^^^^^^
之后,capacity
不是成员函数,只是一个成员:
capacity= v.capacity();
^^
之后,您的复制赋值运算符也需要实际复制所有元素 - 否则它并没有真正...复制任何实质内容。
对于 class 作业,我们必须在模板化的 .h 文件中编写 STL 向量。我尝试 运行 这个和我的所有成员函数都可以工作,除了赋值错误的重载。它位于最底部,是倒数第二个成员函数。
当给我分配任务时,我被要求超载 Vector<T>& operator=(const Vector&v)
template <class T>
class Vector{
private:
int current_size, capacity;
T* arr;
public:
Vector();
~Vector();
unsigned int size();
void grow(); //where does this belong?
void push_back(const T& elt);
void pop_back();
T& at(int pos);
T& front();
T& back();
bool empty();
void insert (const T&elt, int pos);
void erase(int pos);
Vector<T>& operator=(const Vector& v);
T& operator[](int n);
};
template <class T>
Vector<T>& Vector<T>::operator=(const Vector& v){
current_size= v.size();
capacity= v.capacity();
}
错误是"expected unqualified id"错误的行是:
"Vector& Vector::operator=(const Vector& v)"{
这段代码有很多很多问题。
Zeroth,你的缩进风格让代码很难阅读。每次打开新范围时,缩进!
首先,定义成员函数:
template <class T>
typename Vector<T>::T& at(int pos)
template <class T>
Vector<T>:: T& back()
正确的语法是return-type class-name::member-name
。所以这些应该是:
template <class T>
T& Vector<T>::at(int pos)
template <class T>
T& Vector<T>::back()
其次,delete
-ing。 arr
是 T
的动态数组。只有它是动态的。您在多个地方试图删除单个元素:
delete arr[current_size-1];
这是一个无效的操作。
第三,针对你的具体问题,参数v
是const
:
template <class T>
Vector<T>& Vector<T>::operator=(const Vector<T>& v){
这意味着您只能调用 const
限定的成员函数。 size()
不符合 const
条件。您必须添加:
unsigned int size() const;
^^^^^^
之后,capacity
不是成员函数,只是一个成员:
capacity= v.capacity();
^^
之后,您的复制赋值运算符也需要实际复制所有元素 - 否则它并没有真正...复制任何实质内容。