关于错误: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

猜你喜欢

转载自blog.csdn.net/weixin_38337616/article/details/89285311
今日推荐