如果它被定义为 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"
如果我将 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
指针。它只是一个常规功能。
相关文章:
- 使用 cmake 的 Linux 终端上的"Conversion to non-scalar type is requested"错误
- C++线程"Call to non-static member function without an object argument"
- 为什么"non-standard syntax; use '&' to create a pointer to member"在 CTOR 中使用线程?
- 函数参数中的向量"Non-standard syntax"错误
- 哈纳简单折叠"call to non-constexpr function"
- 如果它被定义为 C++ 类中的成员函数,我得到了"non-standard syntax; use '&' to create a pointer to member"
- 'QML Connections: Cannot assign to non-existent Property'尽管情况正好相反
- "conversion from void to non scalar type string"是什么意思?
- Visual Studio 2015:获取"non standard syntax, use '&' to create a pointer to member"错误
- 我收到一个" conversion from ‘std::string (*)[50]’ to non-scalar type ‘std::string’ requested"错误,似乎无法修复它
- 如何修复"initial value of reference to non-const must be an lvalue?"
- 在这种情况下如何解决"Reference to non-static member function must be called"?
- std::variant、包装类和'conversion from ... to non-scalar type ... requested'
- 使用 cvQueryFrame 时出现"conversion from ‘IplImage* {aka _IplImage*}’ to non-scalar type ‘cv::Mat’ reque
- Visual Studio 2015 "non-standard syntax; use '&' to create pointer for member"
- 了解重载运算符。收到"non-standard syntax; use '&' to create a pointer to a member"错误
- Visual Studio 2015 "non-standard syntax; use '&' to create a pointer to member"
- 用于禁用"temporary to non-const reference"错误的 G++ 标志
- Visual Studio 2015 中的"non-standard syntax; use '&' to create a pointer to member"错误
- 如何摆脱 - "warning: converting to non-pointer type 'char' from NULL" ?