C++模板类赋值运算符重载:无参数名时的引用方法咨询
赋值运算符重载无参数名的问题澄清
头文件里的函数声明允许省略参数名——因为声明只需要告诉编译器参数的类型信息,不需要指定名字。但你在实现这个赋值运算符的时候,必须给这个引用参数加上一个名字,才能在函数内部访问它。
比如你头文件里的声明:
template <class Type> const sortedListADT<Type>& operator=(const sortedListADT<Type> &);
这完全合法,但实现的时候得改成这样:
template <class Type> const sortedListADT<Type>& sortedListADT<Type>::operator=(const sortedListADT<Type> &otherList) { // 这里就可以用otherList来引用传入的对象了 if (this != &otherList) { // 避免自赋值导致的错误 destroyList(); copyList(otherList); // 调用你类里的copyList私有函数 } return *this; }
简单总结:声明阶段可以省略参数名,实现阶段必须添加参数名,加完之后就能像普通参数那样用名字引用传入的对象了。
附上你提供的完整头文件代码:
template<class Type> struct nodeType{ Type value; nodeType<Type> *next; nodeType<Type> *prev; }; template <class Type> class sortedListADT { public: const sortedListADT<Type>& operator=(const sortedListADT<Type> &); bool isEmpty() const; bool search(const Type& searchElem) const; void removeElement(const Type& remElem); void insertElement(const Type& newElem); Type front() const; Type back() const; void printInOrder() const; void printRevOrder() const; void destroyList(); sortedListADT(); sortedListADT(const sortedListADT<Type>& otherList); ~sortedListADT(); private: nodeType<Type> *first; nodeType<Type> *last; int numElements; void copyList(const sortedListADT<Type>& otherList); };
内容的提问来源于stack exchange,提问作者David Moorse
相关产品推荐
相关产品推荐

