如果它被定义为 C++ 类中的成员函数,我得到了"non-standard syntax; use '&' to create a pointer to member"

if it's defined as a member function inside a c++ class, I got "non-standard syntax; use '&' to create a pointer to member"

本文关键字:to non-standard member syntax pointer use create C++ 定义 函数 成员      更新时间:2023-10-16

如果我将 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);
....
}
};
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指针。它只是一个常规功能。

相关文章: