c++ - Different kind of objects in an array and getting the type of each
问题描述
I am trying to add different types of objects to an array and I want to get the type of the derived class before casting. Is there a nice solution?
BTW.: This example doesn't work. Type is not set correctly when I check the objects.
pseudo code:
enum Fruit {
APPLE = 0,
BANANA = 1
}
class Fruit {
public:
int type;
}
class Apple : Fruit {
...
}
class Banana : Fruit {
...
}
Apple *apple = new Apple();
apple->type = APPLE;
vector<Fruit*> fruits;
fruits.push_back(apple);
if(fruits[0].type == BANANA) // type always the same ...
static_cast<Banana*>(fruits[0])
**Update: **
I don't understand why this doesn't work.
First, type should be passed to the subclass and is accessible.
Second, I understand why the first and last are 4, but I don't understand why the second elements type is 0 ??
class PolyTest {
public:
int type;
};
class SubA : public PolyTest{
};
class SubB : public PolyTest{
};
std::unique_ptr<SubA> sub = std::make_unique<SubA>();
sub->type = 66;
std::unique_ptr<SubB> subb = std::make_unique<SubB>();
sub->type = 3;
std::vector<PolyTest*> tests;
tests.push_back(sub.get());
tests.push_back(subb.get());
sub->type = 4;
tests.push_back(sub.get());
std::cout << "subtype: " << tests[0]->type << std::endl;
std::cout << "subtype: " << tests[1]->type << std::endl;
std::cout << "subtype: " << tests[2]->type << std::endl;
This returns:
subtype: 4
subtype: 0
subtype: 4
解决方案
As others noted, you can use smart pointers to assure correct destruction and place the base class pointer in the vector. (Note that in my example the range based for needs at least C++11)
class Fruit
{
public:
Fruit(int p_type) { type = p_type;};
int getType() { return type; }
protected:
int type;
};
class Banana : public Fruit
{
public:
Banana() :Fruit(1) {};
};
class Apple : public Fruit
{
public:
Apple() :Fruit(2) {};
};
int main(int argc, char* argv[]) {
std::vector<std::shared_ptr<Fruit>> vec;
auto f1 = std::make_shared<Banana>();
auto f2 = std::make_shared<Apple>();
vec.push_back(f1);
vec.push_back(f2);
for (auto f : vec)
{
std::cout << "my Type is : " << f->getType() << std::endl;
}
}
推荐阅读
- dynamics-crm - 添加子网格和视图以进行字段更新
- iis - 如何将调试诊断工具作为服务运行
- azure - 事件网格不使用逻辑应用触发
- python - 如何使用验证码提交表单
- c#-4.0 - 如何在 CefSharp v57 for Revit 2019 中使用本地 html 文件
- django - 试图让 location_profile 在 __str__ (django) 中显示 location.name
- powershell - 将 powershell 的输出连接到对象 id
- azure-sql-database - 将 BACPAC 导入 _existing_ 数据库
- reactjs - React redux 不维护状态
- javascript - 如何将数组中的值转换为字符串,将数字转换为句子