如何从基调用派生方法
How to call derived method from base
这个问题可能与 this 重复,但我不明白答案如何适用于我的申请。我有一个包含多个派生 class 的基础 class。 class 方法都应具有相同的名称。应用程序收到需要根据数据报类型进行不同解码的 UDP 消息。比如BaseDatagram中的Decode如何调用DerivedDatagramA或DerivedDatagramB中的Decode?
class DerivedDatagramA: public BaseDatagram
{
...
};
class DerivedDatagramB: public BaseDatagram
{
...
};
void BaseDatagram::Decode(uint8_t * buffer)
{
switch(buffer[DATAGRAM_TYPE])
{
case DATAGRAM_TYPE_A:
Decode(buffer); // How to call decode in DerivedDatagramA?
break;
case DATAGRAM_TYPE_B:
Decode(buffer); // How to call decode in DerivedDatagramB?
break;
将BaseDatagram::Decode(uint8_t*)
声明为虚拟,对Decode()
的调用将根据对象类型自动分派给DerivedDatagramA::Decode(uint8_t*)
或DerivedDatagramB::Decode(uint8_t*)
。
这个问题可能与 this 重复,但我不明白答案如何适用于我的申请。我有一个包含多个派生 class 的基础 class。 class 方法都应具有相同的名称。应用程序收到需要根据数据报类型进行不同解码的 UDP 消息。比如BaseDatagram中的Decode如何调用DerivedDatagramA或DerivedDatagramB中的Decode?
class DerivedDatagramA: public BaseDatagram
{
...
};
class DerivedDatagramB: public BaseDatagram
{
...
};
void BaseDatagram::Decode(uint8_t * buffer)
{
switch(buffer[DATAGRAM_TYPE])
{
case DATAGRAM_TYPE_A:
Decode(buffer); // How to call decode in DerivedDatagramA?
break;
case DATAGRAM_TYPE_B:
Decode(buffer); // How to call decode in DerivedDatagramB?
break;
将BaseDatagram::Decode(uint8_t*)
声明为虚拟,对Decode()
的调用将根据对象类型自动分派给DerivedDatagramA::Decode(uint8_t*)
或DerivedDatagramB::Decode(uint8_t*)
。