如果我有这样一个简单的类:
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;
}
};
连同以下运算符(它们不是 friend
s,因为没有私有(private)成员可供访问)。
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;
}
在我的代码的其他地方我有另一个类 A
使用如下所示的方法:
void A::SetVarC(coord<int>& c)
{
m_c = c;
}
(假设 m_c
也有一个 getter)
当我尝试使用我重载的加法和减法运算符调用此方法时:
int x = 1;
int y = 1;
A* a = new A();
coord c1(1,2);
a->SetVarC(c1 - a->GetVarC() + coord<int>(x,y));
我收到一条错误消息,指出没有来自 coord<int>
的已知转换至 coord<int>&
.我可以看到我的减法和加法运算符没有返回引用,但我认为这无关紧要。我正在使用 C++11...移动语义在这里发挥作用吗?
最佳答案
Temporary 不能绑定(bind)到非 const 引用,将 SetVarC
更改为
void A::SetVarC(const coord<int>& c)
{
m_c = c;
}
或
void A::SetVarC(coord<int> c)
{
m_c = std::move(c);
}
关于c++ - 为什么我不能在从算术运算符返回时将此类作为引用传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27702692/