此行是什么意思:
bool operator() (const song& s);
我无法与接线员理解那条线。运算符是c ++中的某种关键字吗?
我们可以在函数范围内使用()代替{}吗?
不,我们不能。 bool operator() (const song& s);
是功能声明,而不是定义。它声明了一个称为operator()
的特殊功能。整体上,operator()
是该功能的名称。以下(const song& s)
是函数参数的列表。该函数的定义如下所示:
#include <iostream>
struct song {
char const* name;
};
struct A {
void operator()(const song& s) {
std::cout << "Received a song: " << s.name << '\n';
}
};
int main() {
A a;
// Here's one way you call that function:
a(song{"Song1"});
// Here's another way
a.operator()(song{"Song2"});
}
这称为运算符重载。您可以详细了解它here。
operator
是一个关键字,用于定义您的类与普通运算符的交互方式。其中包括+,-,*,>>等。
您可以在cppreference处找到完整列表。
其编写方式是关键字operator
,后接运算符。因此,operator+
,operator-
等
operator()
是指函数运算符。如果已定义,则可以像调用函数一样调用对象。
MyClass foo;
foo(); //foo is callable like a function. We are actually calling operator()
在您的示例中,operator()
是函数调用运算符,(const song& s)
是传递给该函数的参数。