Reputation: 11
I'm new here (this is actually my first question here) and looking for some help with a program I'm working on for my Data Structures class.
It is about Operator overloading of = , + and <<.
right now, I'm using a .cpp file that has the function template, including the declarations and definitions:
#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*/
};
In my other .cpp file , I included the previous file and have this following code:
TLIST<char> Char_List,TempChar1, TempChar2;
Char_List + 'W' + 'E' + 'L' + 'C' + 'O' + 'M' + 'E'; // chaining
Now, I'm trying to overload the "+" operator. I am at a point where I asked the professor if my declaration is correct and he told me it is but I'm missing something inside the definition:
template <class t_type>
TLIST<t_type> & TLIST<t_type>::operator+(const t_type &rhs)
{
TLIST <t_type> lhs;
lhs += rhs;
return *this;
}
I keep getting this error :
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)
which is understandable, since I'm trying to have a template of chars on lhs and just a char on rhs (correct me if I'm wrong).
How should I go ahead and fix it?
Thank you.
Upvotes: 1
Views: 692
Reputation: 208446
There are a couple of things wrong with that operator+
:
template <class t_type>
TLIST<t_type> & TLIST<t_type>::operator+(const t_type &rhs)
{
TLIST <t_type> lhs;
lhs += rhs;
return *this;
}
The first thing is that you are returning a reference, but creating a variable inside the function then modifying it and finally returning a reference to this
(on which you have not applied any operation!!). Your implementation is an expensive version of:
return *this;
Then the definition of addition is wrong, you create a TLIST
using the default constructor, and then attempt to add the argument. This is not adding to this object, but to an empty TLIST
!.
Then there is the fact that your code depends on operator+=
, but that operator does not seem to be defined.
Upvotes: 1
Reputation: 56577
In the line lhs += rhs;
you expect the compiler to know what +=
means. However, you did not define the operator +=
, so the compiler doesn't know how to implement it. One solution is to define the operator+=
first and keep the operator+
as it is.
Upvotes: 0