如何關於interface?
class A
{
public:
virtual void perform() = 0;
};
class B : public A
{
public:
void perform() { ... }
};
// Same for C, and D
所以你的回調會再看看這樣的:
MyCallBack(A& performer)
{
performer.perform();
}
如果你不能改變回調的簽名,又有怎樣的abstract factory pattern:
function A* AFactory(int type)
{
switch(type)
{
case 1: return new B(); // Assuming B, C, D all derive from A
case 2: return new C();
case 3: return new D();
default: return nullptr; // nullptr is a c++11 thing. Use NULL, if you're still on C++03
}
}
,然後回調...
MyCallBack(int type)
{
std::unique_ptr<A> obj(AFactory(type)); // this will automatically release the memory once it falls out of scope
obj->perform();
}
不應該通過指針(即MyCallBack(A * performer))指向'MyCallBack(A&performer)',然後用'performer-> perform()'調用它? – 2012-03-13 18:56:43
通過引用基類來引用派生類是合法的。當然,如果一個A *被傳入,那麼A *就是他必須使用的。在可能的情況下,應該更喜歡引用指針。 – luke 2012-03-13 19:01:10