c++ - 调用没有名称的方法

标签 c++

我需要能够使用我正在编写的代码运行这一行:

 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/

相关文章:

C++ 和 SQL server Job 有可能吗?如何 ?

c++ - 我在这里违反了 OOP 设计指南吗?几个有趣的设计泡菜

c++ - 为括号中的数字解析字符串的更好方法?

c++ - 如何对 unique_ptr 列表进行排序?

c++ - 如何在arduino uno中同时使用水流量传感器和GSM(SIM900)?

c# - 从非常大的 HTML 文件中解析特定元素

c++ - 我怎样才能通过 getchar();不按回车,让它自动?

c++ - 有没有办法在编译时使用宏从其他地方向枚举添加额外的值?

c++ - boost::hana 如何检查类型是否为 std::optional?

c++ - 如何使用 openvdb(并行)foreach 访问多个网格?