如何关于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