【问题标题】:Object has type qualifiers that prevent match (function overload not found)对象具有阻止匹配的类型限定符(未找到函数重载)
【发布时间】:2013-03-16 00:39:52
【问题描述】:

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

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(),但这也是错误的。

【问题讨论】:

    标签: c++ oop operator-overloading


    【解决方案1】:

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

    当它说“对象有类型限定符等等等等”时,这意味着一个对象有太多的constvolatile 限定符来访问一个函数。

    另外,由于您发布了错误的摘要,我假设您使用的是 Visual Studio。 Visual Studio 在“错误”窗口中显示错误摘要。转到 View->Output 以查看其可怕细节的完整错误,它应该告诉您哪个变量是问题,并且由于它是 constness 而无法调用该函数。

    【讨论】:

      【解决方案2】:

      尝试改变:

      int value();  //Returns value
      

      收件人:

      int value() const;  //Returns value
      

      【讨论】:

        【解决方案3】:

        在这个重载的operator= 中,other 是一个const 引用。您只能在此对象上调用标记为 const 的成员函数。由于value()函数只是返回val,并没有修改对象,所以应该标记为const

        int value() const;
        

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

        【讨论】:

        • 哦,我想我永远也想不通,谢谢你的解释。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-11
        相关资源
        最近更新 更多