#include <iostream>
#include <string>
#include <map>
#include <vector>
class base {};
class derived1 : public base
{
public:
unsigned short n;
derived1()
{
n = 2;
}
};
class derived2 : public base {};
void main()
{
// way 1
{
std::vector<derived1> a1;
std::vector<derived2> a2;
std::map<std::string, base*> b;
a1.push_back(derived1());
b["abc"] = &a1.at(0);
std::cout<<(dynamic_cast<derived1*>(b.find("abc")->second))->n<<std::endl;
}
// way 2
{
std::map<std::string, base*> b;
b["abc"] = new derived1();
std::cout<<dynamic_cast<derived1*>(b.find("abc")->second)->n<<std::endl;
delete dynamic_cast<derived1*>(b.find("abc")->second);
}
}
错误是“'dynamic_cast':'base' 不是多态类型”。应该怎么做才能解决这个问题?方式 1 和方式 2 是否都已正确清理?