天天看點

錯誤: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指針,這也就是靜态成員函數指針和普通函數指針沒有差別的原因。
脫離本問題,我們談談成員函數指針和普通函數指針的差別:
具體可參考這篇部落格,講的很好,侵删:
點選打開連結
下一篇: 【Java】封裝

繼續閱讀