c++ - 为什么我不能在从算术运算符返回时将此类作为引用传递?

标签 c++ c++11 operator-overloading pass-by-reference

如果我有这样一个简单的类:

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/

相关文章:

c++ - 如何重载间接运算符? (C++)

c++ - friend 功能如何运作

c++ - 使用 Makefile 运行的程序中出现 Xcode 链接错误

c++ - 使 cpp(C 预处理器)删除 Mac OS X 上的 C++ 注释

c++ - 在没有 std::index_sequence 的人工层的情况下就地解压 std::tuple

c++ - 从 lambda 内部调用函数返回

c++ - 隐式转换为 basic_istream/ifstream/ofstream 的 bool 在 Visual Studio 2013 中不起作用

c++ - 重载新/删除

使用 C++ 开发 iPhone 应用程序?

c++ - 在将参数传递给基类时使用 std::move()