簡體   English   中英

C ++了解函子多態性

[英]C++ Understanding Functors Polymorphism

我嘗試實現多態仿函數對象(純抽象基類和子代)僅出於理解目的。 我的目標是創建許多使用純虛函數的不同實現的基類對象。

當我創建基類的指針並將其設置為新的子類時,我無法將對象作為函數調用。 錯誤是:

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

當取消引用a時,您丟棄了多態性,應該調用foo::operator()而不是bar::operator() ,從而引發純虛擬函數調用異常

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM