2013-05-19 22 views
0

我知道下面的代碼不會編譯,但是我發佈了它,因爲它體現了我正在嘗試完成的任務。稍後在C++中實現一般方法

typedef struct { 
    void actionMethod(); 
}Object; 

Object myObject; 

void myObject.actionMethod() { 
    // do something; 
} 

Object anotherObject; 

void anotherObject.actionMethod() { 
    // do something else; 
} 

main() { 
    myObject.actionMethod(); 
    anotherObject.actionMethod(); 
} 

基本上我想要的是某種委託。有沒有一些簡單的方法來做到這一點?我不能包含<functional>標題,也不能使用std::function。我怎樣才能做到這一點?

+4

你可以讓對象存儲一個函數指針。 –

+0

我該怎麼做? – user2142733

回答

1

例如:

#include <iostream> 

using namespace std; 

struct AnObject { 
    void (*actionMethod)(); 
}; 

void anActionMethod() { 
    cout << "This is one implementation" << endl; 
} 

void anotherActionMethod() { 
    cout << "This is another implementation" << endl; 
} 

int main() { 
    AnObject myObject, anotherObject; 
    myObject.actionMethod = &anActionMethod; 
    anotherObject.actionMethod = &anotherActionMethod; 

    myObject.actionMethod(); 
    anotherObject.actionMethod(); 

    return 0; 
} 

輸出:

This is one implementation 
This is another implementation 
+0

謝謝!工作! – user2142733

1

Object一個函數指針構件:

struct Object { 
    void (*actionMethod)(); 
}; 

在此,構件actionMethod是起作用不接受參數的指針並沒有返回。那麼,讓我們說你有一個名爲foo功能,可以設置actionMethod在這個功能點,像這樣:

Object myObject; 
myObject.actionMethod = &foo; 

,你可以接着用myObject.actionmethod()調用。