我有一个C++应用程序,它具有以下类:
class AAAclass BBB 继承自 AAAclass CCC 继承自 AAAclass DDD 继承自 CCC(所有课程都标记为public)
现在我有以下地图:
map <DWORD, AAA*>
Run Code Online (Sandbox Code Playgroud)
我AAA在mapa中找到了一个对象DWORD id,但现在我想知道它的类型是什么AAA:
这将是逻辑:
if(AAA is BBB)
{
...
}
if(AAA is CCC)
{
...
}
if(AAA is DDD)
{
...
}
Run Code Online (Sandbox Code Playgroud)
你知道如何用C++编写它(不添加多态函数getType())吗?
要求这表明你做错了.您正在尝试复制虚拟方法的发明内容.只需在基类中放置一个虚方法即可.
class AAA
{
public:
virtual void DoSomething() = 0;
}
class BBB : public AAA
{
public:
void DoSomething() { ... }
}
class CCC : public AAA
{
public:
void DoSomething() { ... }
}
class DDD : public AAA
{
public:
void DoSomething() { ... }
}
Run Code Online (Sandbox Code Playgroud)
在您的调用代码中,您的逻辑很简单:
// no need for if() blocks. it's the point of virtual methods.
AAA* somePointer;
...
somePointer->DoSomething();
Run Code Online (Sandbox Code Playgroud)
我意识到你可能不能只将你当前的"dosomething"代码复制/粘贴到这里.但这是您应该在此方案中使用的模式.或许DoSomething这样做更有意义的GetSomeInfo是,调用者可以使用它做任何需要做的事情.此模式的具体用法取决于您的上下文.