【问题标题】:C++ Understanding Functors PolymorphismC++ 理解函子多态性
【发布时间】:2015-07-14 20:13:27
【问题描述】:

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

当我创建一个基类的指针并将它设置为一个新的子类时,我不能将对象作为函数调用。错误是:

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()”应该调用它。

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

【问题讨论】:

    标签: c++ polymorphism functor


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      当您取消引用 a 时,您丢弃了多态性,应该调用 foo::operator() 而不是 bar::operator(),因此抛出了纯虚函数调用异常

      【讨论】:

      • 这基本上是错误的。取消引用不会“抛弃多态性”。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多