我已经定义了一个模板类和重载运算符。编译时,我收到以下错误消息:
error C2677: binary '+=' : no global operator found which takes type 'Class' (or there is no acceptable conversion)
下面是该类的相关代码:
template<int foo>
class Class
{
private:
int value;
public:
template<int other_foo>
friend class Class;
// Constructors and copy constructors for several data type
// including other possibilities of "foo"; all tested.
Class& operator+=(const Class& x)
{
value += x.value;
return *this;
}
template<class T>
Class& operator+=(const T& x)
{
this += Class(x);
return *this;
}
};
如果我创建两个对象,例如 Class<3>
; operator +=
工作正常,做正确的事。
但是,如果我有一个 Class<3>
的对象和 Class<2>
之一,我得到上面的错误,它指向为 T 定义“+=”的行 [foo 的不同值的构造函数工作正常并且也经过测试]。
我做错了什么?我该如何解决这个错误? 运算符已定义,就在上面几行。
最佳答案
假设必要的构造函数确实存在并且可以正常工作,那么您发布的代码中的错误是
this += Class(x);
它试图修改不可变指针 this
的值。应该是
*this += Class(x);
关于c++ - 模板化重载运算符的编译错误 "No global operator found",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30101418/