如果它被定义为c ++类中的成员函数,我得到了“非标准语法;使用'&'创建指向成员的指针“[复制]

问题描述 投票:0回答:1

如果我将sfun()定义为类中的成员函数,我得到了编译错误消息:“非标准语法;使用'&'创建指向成员的指针”在“sort(intervals.begin()”行,intervals.end(),sfun);“

但是,如果我把它放在课堂之外,那很好。为什么?

struct Interval {
    int start;
    int end;
    Interval() : start(0), end(0) {}
    Interval(int s, int e) : start(s), end(e) {}
};

class Solution {
    bool sfun(const Interval &a, const Interval &b) {
        return a.start < b.start;
    }

    public:   

    vector<Interval> merge(vector<Interval>& intervals) {

        sort(intervals.begin(), intervals.end(), sfun);
    ....
    }
};
c++ syntax compilation
1个回答
1
投票
class Solution {
    bool sfun(const Interval &a, const Interval &b) {
        return a.start < b.start;
    }

sfun是会员功能。您可以访问其中的隐式this指针。因此,您可以使用签名bool sfun(Solution* this, const Interval& a, const Interval& b)将其粗略地视为一个函数。

当你把sfun放在类之外时它会起作用,因为它不是一个成员函数,而是一个常规的自由函数。它的签名将是bool sfun(const Interval &a, const Interval &b)

你也可以使sfun成为static的功能:

class Solution {
    static bool sfun(const Interval &a, const Interval &b) {
        return a.start < b.start;
    }

static成员函数是“类函数”。它们不适用于类的实例。没有隐含的this指针。这只是一个常规功能。

© www.soinside.com 2019 - 2024. All rights reserved.