c++ - 模板化重载运算符的编译错误 "No global operator found"

标签 c++ templates compiler-errors

我已经定义了一个模板类和重载运算符。编译时,我收到以下错误消息:

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/

相关文章:

c++ - 如何使用 C/C++ 获取原始相机数据?

c# - 从 C# 应用程序执行 C++ 函数

c++ - 为什么无法删除 {}?为什么char类型的变量不能传递?

c++ - 使用自定义 header 进行 ffplay 编译

java - 使用Gradle添加Maven存储库以期望依赖

c++ - boost::iostream bzip2_decompressor 不解压缩由 bzip2_compressor 压缩的文件

c++ - 如何从函数返回数组?

asp.net-mvc - 在 ASP.NET MVC 项目上使用远程 Web 设计器的过程

c++ - "static"在声明全局模板函数的上下文中意味着什么?

ios - 如何解决此 Spritekit (Swift 3) 错误?