簡體   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