C++ 理解仿函数多态性

标签 c++ polymorphism functor

我尝试实现多态仿函数对象(纯抽象基类和子类)仅用于理解目的。我的目标是创建许多使用纯虚函数的不同实现的基类对象。

当我创建基类的指针并将其设置为等于新的子类时,我无法将该对象作为函数调用。错误是:

main.cpp:29:7: error: ‘a’ cannot be used as a function

代码如下:

#include <iostream>

class foo{
public:
    virtual void operator()() = 0;
    virtual ~foo(){}
};

class bar: public foo{
public:
    void operator()(){ std::cout << "bar" << std::endl;}
};

class car: public foo{
public:
    void operator()(){ std::cout << "car" << std::endl;}
};


int main(int argc, char *argv[])
{

    foo *a = new bar;
    foo *b = new car;

    //prints out the address of the two object: 
    //hence I know that they are being created
    std::cout << a << std::endl;
    std::cout << b << std::endl;

    //does not call bar() instead returns the error mentioned above
    //I also tried some obscure variation of the theme:
    //*a(); *a()(); a()->(); a->(); a()();
    //just calling "a;" does not do anything except throwing a warning
    a();

    //the following code works fine: when called it print bar, car respectivly as expected
    // bar b;
    // car c;
    // b();
    // c();

    delete b;
    delete a;
    return 0;
}

我目前的理解是“foo *a”存放的是函数对象“bar”在a中的地址(如cout语句所示)。因此取消引用它“*a”应该提供对“a”指向的函数的访问并且“*a()”应该调用它。

但事实并非如此。谁能告诉我为什么?

最佳答案

因为您有一个指向 a 的指针,您必须取消引用它以调用 () 运算符:

(*a)(); // Best use parentheseis around the dereferenced instance

关于C++ 理解仿函数多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30047137/

相关文章:

c++ - 我需要在 C++ 中创建一个简单的回调?我应该使用 boost::function 吗?

使用 protected 构造函数的 C++ 常量实例?

java - 多态java思想

OOP 设计 - 许多对象每个都与其他对象的有限子集具有独特的交互

java - Jdialog 将用户凭据传回其包含的 JFrame?或者,JFrame 从其 JDialog 获取凭据?

c++ - 将 C++ 重载函数指针提升到函数对象

c++ - 无法理解 C++ `virtual`

C++:使用io.post和bind命令从boost线程在主线程中执行函数

C++11:基于范围的 for 循环遍历由模板化迭代器描述的范围

haskell - 对 Maybe 值列表进行操作