繁体   English   中英

对象具有防止匹配的类型限定符(未找到函数重载)

[英]Object has type qualifiers that prevent match (function overload not found)

我有一个简单的类,旨在将整数转换为字节数组。

class mc_int {
    private: 
        int val;      //actual int
    public: 
        int value();  //Returns value
        int value(int);  //Changes and returns value
        mc_int();  //Default constructor
        mc_int(int);//Create from int
        void asBytes(char*); //generate byte array

        mc_int& operator=(int);
        mc_int& operator=(const mc_int&);

        bool endianity;  //true for little
};

为了转换和简化用法,我决定添加operator=方法。 但是我认为我对mc_int& operator=(const mc_int&); 是不正确的。

mc_int& mc_int::operator=(const mc_int& other) {
            val = other.value();  
            //    |-------->Error: No instance of overloaded function matches the argument list and object (object has type quelifiers that prevent the match)
}

这可能是什么? 我试图使用other->value() ,但这也是错误的。

您的成员函数value()不是const函数,这意味着它有权修改成员,并且不能在const对象上调用。 由于我假设您是只读的,因此将其更改为int value() const; 然后,您可以在mc_int const实例上调用它,并确保您不会意外更改任何成员。

当它说“对象具有类型限定符等等”时,表示对象具有太多的constvolatile限定符,无法访问函数。

另外,由于您发布了错误摘要 ,因此我假设您正在使用Visual Studio。 Visual Studio在“错误”窗口中显示错误摘要。 转到查看- >输出,看看在他们的可怕细节,这应该告诉你哪个变量是问题,完全错误,它不能调用该函数,因为它是const湖。

在此重载operator=otherconst引用。 您只能在该对象上调用标记为const成员函数。 由于value()函数仅返回val且不修改对象,因此应将其标记为const

int value() const;

这表示此函数不会修改对象的状态,因此可以在const对象上调用。

尝试更改:

int value();  //Returns value

至:

int value() const;  //Returns value

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM