C ++了解函子多态性 [英] C++ Understanding Functors Polymorphism

查看:72
本文介绍了C ++了解函子多态性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to implement polymorphic functor objects (pure abstract base class and children) for understanding purposes only. My goal is to create many objects of the base class that use different implementations of the pure virtual functions.

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

When I create a pointer of the base class and set it equal to a new child class, I can not call the object as a function. The error is:

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()"应调用它.

My current understanding is that "foo *a" stores the address of of the function object "bar" in a (as shown by the cout statement). Hence dereferencing it "*a" should provide access to the function to which "a" is pointing to and "*a()" should call it.

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

But it does not. Can anyone tell me why?

推荐答案

由于有a的指针,因此必须取消引用它才能调用()运算符:

Since you have a pointer for a, you must dereference it to call the () operator:

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

这篇关于C ++了解函子多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆