我是新来的(这实际上是我在这里的第一个问题),正在为我的数据结构类(class)寻找一些帮助。
它是关于 = 、 + 和 << 的运算符重载。
现在,我正在使用一个包含函数模板的 .cpp 文件,包括声明和定义:
#include <iostream>
using namespace std;
template <class t_type>
class TLIST {
public:
TLIST();
TLIST(const TLIST<t_type> &);
bool IsEmpty();
bool IsFull();
int Search(t_type);
TLIST<t_type> & TLIST<t_type>::operator+(const t_type &rhs);
void Remove(const t_type);
// TLIST<t_type> & operator=(const TLIST<t_type> &);
// friend operator<<(ostream &, TLIST<t_type> &);
void Double_Size();
/*other functions you may want to implement*/
private:
t_type *DB;
int count;
int capacity;
/*additonal state variables you may wish add*/
};
在我的其他 .cpp 文件中,我包含了以前的文件并具有以下代码:
TLIST<char> Char_List,TempChar1, TempChar2;
Char_List + 'W' + 'E' + 'L' + 'C' + 'O' + 'M' + 'E'; // chaining
现在,我正在尝试重载“+”运算符。我当时问教授我的声明是否正确,他告诉我是的,但我在定义中遗漏了一些东西:
template <class t_type>
TLIST<t_type> & TLIST<t_type>::operator+(const t_type &rhs)
{
TLIST <t_type> lhs;
lhs += rhs;
return *this;
}
我一直收到这个错误:
Error 1 error C2676: binary '+=' : 'TLIST' does not define this operator or a conversion to a type acceptable to the predefined operator c:\users\negri\dropbox\visual studio\projects\assignment 1 (tlist2)\assignment 1 (tlist2)\tlist.cpp 53 1 Assignment 1 (TLIST2)
这是可以理解的,因为我试图在 lhs 上有一个字符模板,而在 rhs 上只有一个字符(如果我错了请纠正我)。
我应该如何继续修复它?
谢谢。
最佳答案
operator+
有几个问题:
template <class t_type>
TLIST<t_type> & TLIST<t_type>::operator+(const t_type &rhs)
{
TLIST <t_type> lhs;
lhs += rhs;
return *this;
}
第一件事是您要返回一个引用,但是在函数内部创建一个变量然后修改它并最终返回对this
的引用(您在其中有未应用任何操作!!)。您的实现是以下的昂贵版本:
return *this;
那么加法的定义错误,您使用默认构造函数创建了一个TLIST
,然后尝试添加参数。这不是添加到this对象,而是添加到一个空的TLIST
!
还有就是你的代码依赖于operator+=
,但是那个operator好像没有定义。
关于c++ - 使用模板的运算符重载赋值 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23728418/