在c ++中将类调用为函数

时间:2016-02-25 12:48:54

标签: c++ class

在python中你可以定义一个A类

class A(object):
    .....

    def __call__(self, bar):
        #do stuff with bar
        ....

允许我像这样使用它:

bar = "something"
foo = A()
foo(bar)

我想在c ++中做同样的事情,但我没有找到任何东西,这是可能的还是我忽略了什么?

1 个答案:

答案 0 :(得分:1)

类的名称在C ++中为构造函数保留。您可以使用所需类型的参数创建构造函数,但它始终会创建该类的新实例。 如果您需要执行一些未实例化该类的任务,请使用其他名称创建一个方法。

class A {
    ...
public:
    A(); // Constructor with no parameters
    A(BarType bar); // Constructor with parameter BarType
    void someMethod(BarType bar); // Method that takes bar and performs some operation
}

用法:

BarType bar = BarType();
A aInstance = A(bar);

执行某些任务而不使用参数进行实例化:

A aInstance = A();
BarType bar = BarType();
aInstance.someMethod(bar);