2015-05-05 55 views
5

我嘗試實現多態函子對象(純粹的抽象基類和子類)僅用於理解目的。我的目標是創建許多基類的對象,它們使用純虛函數的不同實現。C++瞭解函子多態性

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

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; 
} 

我目前的理解是,「富*一個」存儲如由在一個功能對象「BAR」的地址( cout聲明)。因此,取消引用它「* a」應該提供對「a」指向的函數的訪問權限,「* a()」應該調用它。

但它沒有。誰能告訴我爲什麼?

回答

6

既然你有a指針,必須取消對它的引用調用()操作:

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