自从我用 C++ 编程以来,已经有3年了。我的多态性不起作用:当我map<string, Base>
将我的ArmyBase
和NavyBase
对象Base
添加到 时,它们将它们转换为对象map
,因此GetDescription()
返回一个空字符串,而不是我通过ArmyBase::SetDescription()
and设置的值NavyBase::SetDescription()
。这是极其粗糙的伪代码:
class Base
{ protected:
string STR__Description; // Pardon my non-standard style
public:
virtual
string GetDescription()
{ return STR__Description;
}
void SetDescription( string str__Description )
{ STR__Description = str__Description;
}
}
class ArmyBase: public Base
{ public:
string GetDescription()
{ return STR__Description + " (Army)";
}
}
class NavyBase: public Base
{ public:
string GetDescription()
{ return STR__Description + " (Navy)";
}
}
听起来map<string, Base*>
会导致内存泄漏,我宁愿不升级中期项目以使用shared_ptr
. 将派生类实例存储在正确“破坏”它们的容器中是否允许我使用指针map
进行多态性而不会有内存泄漏的风险?
Base base;
ArmyBase base_Army;
set<ArmyBase> set__ArmyBases;
map<string, Base*>::iterator iter_Bases;
map<string, Base*> map__Bases;
NavyBase base_Navy;
set<NavyBase> set__NavyBases;
...
while( ... )
{ base_Army = ArmyBase();
base_Navy = NavyBase();
...
set__ArmyBases.insert( base_Army );
map__Bases.insert( pair<string, Base*>( "Boca Raton", &base_Army ) );
...
set__NavyBases.insert( base_Navy );
map__Bases.insert( pair<string> Base*>( "NAS Pensacola", &base_Navy ) );
...
base = iter_Bases->second;
std::cout << ..." " << base->GetDescription() << std::endl;
}
所需的输出map__Bases
:
Boca Raton ... (Army)
NAS Pensacola ... (Navy)
...