我需要能够使用我正在编写的代码运行这一行:
euro(2, Regular)
euro
是来自名为 MainControl
的类的对象,并且我定义了一个枚举:
enum VoterType { All, Regular, Judge };
基本上我明白我们想要使用名为MainControl
的类中的一些方法。 ,但我没有看到应该使用的方法的名称?
鉴于此函数返回 void
,声明在类 MainControl
中到底应该是什么样子? ?
最佳答案
MainControl
类正在实现自定义 overloaded operator ,即“函数调用运算符”。
How exactly is the declaration supposed to look like in the class MainControl?
方法签名应该类似于:
class MainControl {
// ...
public:
void operator()(int, VoterType);
};
When a user-defined class overloads the function call operator, operator(), it becomes a FunctionObject type.
简而言之,您的类实例 (euro
) 是一个 FunctionObject,并且可以简单地调用该特定方法(例如):
euro(2, VoterType::Regular)
附加说明
为了完整起见,“运算符方法”就像另一种方法(这里没有黑魔法)。
事实上,您甚至可以使用完整名称来调用它:
euro.operator()(2, VoterType::Regular);
但是语法变得相当难看。
关于c++ - 调用没有名称的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56737262/