我該如何解決這個問題?我想執行正確的方法。有什麼辦法可以解決這個問題嗎? 我想在一個循環中執行方法。C++繼承,怎麼解決這個問題?
class Base
{
public:
void something() {}
};
class Child : public Base
{
public:
void something() {}
};
class SecondChild : public Base
{
public:
void something() {}
};
std::vector<Base*> vbase;
Child * tmp = new Child();
vbase.push_back((Base*) tmp);
SecondChild * tmp2 = new SecondChild();
vbase.push_back((Base*) tmp);
for (std::vector<Base*>::iterator it = vbase.begin(); it != vbase.end(); it++)
{
//here's problem, I want to execute proper method "something", but only I can do is execute Base::something;
(*it)->something();
}
我不知道怎麼投的類型,當我到了基類的許多兒童。
您需要虛擬功能。在使用智能指針時,請使用智能指針。 – chris
Dupe? http://stackoverflow.com/questions/3328022/confused-with-c-inheritance?rq=1 – chris