Reputation: 23
I'm trying to pass an object as a parameter of an overloaded operator+ (and the class is a template class) but it's giving me an error which states:
error C2955: 'Kvader': use of class template requires template argument list
this is my class:
template <class Q>
class Kvader {
private:
Q a, b, c;
public:
Kvader(const Kvader &temp);
Kvader operator+(Kvader);
};
and this is my overloaded+ method:
template <class Q>
Kvader Kvader<Q>::operator+(Kvader<int> temp) {
a += temp.a;
b += temp.b;
c += temp.c;
return *this;
}
I thought that
Kvader Kvader<Q>::operator+(Kvader<int> temp)
would suffice as the argument list. What am I doing wrong?
In my main i'm just making 2 objects, (the second one calls the copy constructor) and then I try to add them together.
int main(){
Kvader<int> object1, object2(object1);
object1 = object1 + object2;
return 0;
}
Upvotes: 1
Views: 76
Reputation: 4196
This code contains a few errors:
1) Kvader<Q> Kvader<Q>::operator+(Kvader<int> temp)
You need to specify the argument list for the return type as well.
2) Kvader<Q> operator+(Kvader<int>);
Same as 1) + change the argument type to Kvader<int>
instead of the generic Kvader<Q>
.
3) Kvader<Q>(const Kvader<Q> &temp);
Same as 1).
4) Specify a default constructor for Kvader<Q>
else the creation statement in main()
is going to fail.
5) Also, operator+(const T&)
should return a reference to allow for operator chaining. It also typically takes a const reference to avoid unnecessary copying.
6) Finally, unless you have a particular reason for doing it the way you've done it, things like operator+(const Kvader<Q>&)
should be defined in a generic fashion first, and then be specialized, when there is a need to do so. The way you've written it, operator+(cont Kvader<int>&)
only works for those types where the Q
type of the this
object can be added to an int
. What you probably wanted to achieve, was to enable a specialization of Kvader
with any certain parameter to be added to Kvader
's with the same exact parameter. Then, you can create specializations for specific Q
types, such as int
.
I suggest you actually read up on class and function templates! They can be confusing at times, indeed.
Complete code:
template <class Q>
class Kvader {
private:
Q a, b, c;
public:
Kvader() {}
Kvader(const Kvader<Q> &temp);
Kvader& operator+(const Kvader<Q>& temp);
};
template <class Q>
Kvader<Q>& Kvader<Q>::operator+(const Kvader<Q>& temp) {
a += temp.a;
b += temp.b;
c += temp.c;
return *this;
}
template<class Q>
Kvader<Q>::Kvader(const Kvader<Q> &temp)
{}
int main(){
Kvader<int> object1, object2(object1);
object1 = object1 + object2;
return 0;
}
Upvotes: 1