mardi 30 décembre 2014

Why can't I pass this class as a reference when returned from arithmetic operators?

If I have a simple class like this:



template<typename T>
class coord
{
public:

coord() : x(0), y(0)
{
}

coord(T X, T Y) : x(X), y(Y)
{
}

T x;
T y;

coord& operator-=(const coord& rhs)
{
(*this).x -= rhs.x;
(*this).y -= rhs.y;
return *this;
}

coord& operator+=(const coord& rhs)
{
(*this).x += rhs.x;
(*this).y += rhs.y;
return *this;
}
};


Along with the following operators (they're not friends because there's no private members to access).



template<typename T = int>
inline coord<T> operator-(coord<T> lhs, const coord<T>& rhs)
{
lhs -= rhs;
return lhs;
}

template<typename T = int>
inline coord<T> operator+(coord<T> lhs, const coord<T>& rhs)
{
lhs += rhs;
return lhs;
}


Elsewhere in my code I have another class A with a method that looks like this:



void A::SetVarC(coord<int>& c)
{
m_c = c;
}


(assume there's a getter for m_c as well)


When I try to invoke this method using the addition and subtraction operators I overloaded:



int x = 1;
int y = 1;

A* a = new A();

coord c1(1,2);

a->SetVarC(c1 - a->GetVarC() + coord<int>(x,y));


I get an error that there's no known conversion from coord<int> to coord<int>&. I can see that my subtraction and addition operators aren't returning references, but I thought that wouldn't matter. I am using C++11... are move semantics coming into play here?


Aucun commentaire:

Enregistrer un commentaire