關於錯誤:reference to non-static member function must be called

問題:

今天刷牛客這道題的時候:

題目描述:

輸入一個正整數數組,把數組裏所有數字拼接起來排成一個數,打印能拼接出的所有數字中最小的一個。例如輸入數組{3,32,321},則打印出這三個數字能排成的最小數字爲321323。

這是我的代碼:

class Solution {
public:
    bool bijiao(int a, int b)
    {
        string sb = to_string(a)+to_string(b);
        string sa = to_string(b)+to_string(a);
        if(sb<sa)
            return true;
        else
            return false;
	}
        
    string PrintMinNumber(vector<int> numbers) {
        sort(numbers.begin(), numbers.end(), bijiao);   // 提示錯誤出在此處
        string s = "";
        for(int i=0; i<numbers.size(); ++i)
        {
            s += to_string(numbers[i]);
		}
        return s;
    }
};

錯誤提示爲:

reference to non-static member function must be called: sort(numbers.begin(), numbers.end(), bijiao);

解決:

我們先看一下sort函數的定義:

template <class RandomAccessIterator, class Compare>
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp)
參數comp的解釋:

comp: Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool.The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.The function shall not modify any of its arguments. This can either be a function pointer or a function object.

在我寫的這段代碼中,sort(numbers.begin(), numbers.end(), bijiao)中第三個參數是一個函數指針,然而bijiao函數是一個非靜態成員函數,非靜態成員函數指針和普通函數指針是有區別的。具體區別,我們後文會講到,然而靜態成員函數指針和普通函數指針沒有區別,所以此處將

bool bijiao(int a, int b);

改爲

static bool bijiao(int a, int b);

即可通過編譯

或者將bijiao函數放在類外,改爲全局普通函數亦可通過編譯。

接下來,我們解釋成員函數指針和普通函數指針的不同:我們知道bijiao成員函數擁有一個 implicit parameter,bool bijiao(Solution* this, int a, int b) 所以,它和普通函數指針是有本質區別的,畢竟它們的參數列表都不相同。而靜態成員函數沒有this指針,這也就是靜態成員函數指針和普通函數指針沒有區別的原因。脫離本問題,我們談談成員函數指針和普通函數指針的區別:

具體可參考這篇博客,講的很好,侵刪:

http://www.cnblogs.com/AnnieKim/archive/2011/12/04/2275589.html


原文:https://blog.csdn.net/u010982765/article/details/79021426

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章