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

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

本文关键字:重载 函数 类型 对象      更新时间:2023-10-16

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

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_intconst实例上调用它,它保证你不会意外地改变任何成员。

当它说"对象有类型限定符什么的"时,这意味着对象有太多的constvolatile限定符来访问函数。

另外,既然你发布了一个错误的摘要,我假设你正在使用visual studio。Visual Studio在"Error"窗口中显示错误摘要。转到View->Output查看完整的错误细节,它应该告诉您哪个变量是问题所在,并且由于它的const性而无法调用该函数。

尝试更改:

int value();  //Returns value

:

int value() const;  //Returns value

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

int value() const;

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