代码选择器在运行时使用inheritage [英] Code selector using inheritage during runtime
问题描述
有没有办法在容器中插入抽象类?
是否有基类访问派生类的方法?使用虚拟函数。
此示例代码是否有正确工作方式,并且控制台能够 bark ?
有一种方法可以使<
Is there a way to insert an abstract class inside a container? No.
Is there a way for a base class to access derived classes? Using virtual functions.
Is there a way for this example code to work properly and the console to bark?
Is there a way for the vector
container to keep the instances and not references/pointers?
将指针存储在 std:
Storing pointers inside the std::vector
will only be safe if I use reference counters to the instances, which is my last resort. Do I miss something?
class CAnimal
{
public:
virtual void soundsLike()
{
cout<<"Base function\n";
}
};
class CDog: public CAnimal
{
public:
void soundsLike()
{
cout<<"Woof\n";
}
};
class CZoo
{
public:
std::vector<CAnimal> animalList;
void addDog()
{
animalList.push_back(CDog());
}
};
控制台输出基本功能消息:
Console outputs the base function message:
int main(int argc, char* argv[])
{
CZoo nationalPark;
nationalPark.addDog();
nationalPark.animalList.front().soundsLike(); //Calls the base function.
return 0;
}
推荐答案
=http://en.cppreference.com/w/cpp/memory/unique_ptr =nofollow> std :: unique_ptr
You could use std::unique_ptr
std::vector< std::unique_ptr<CAnimal> > zoo;
zoo.push_back(new CDog());
zoo[0]->soundsLike();
是不是? unique_ptr会处理你的破坏。
Is it bad? unique_ptr will handle the destruction for you.
我不认为你可以使用引用。另外我不认为你可以使它树皮目前。只有woof。
I don't think you can use references. Also I don't think you can make it "bark" currently. Only "woof".
这篇关于代码选择器在运行时使用inheritage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!