我正在制作一个农业模拟器,其中有“Produce”类,它继承了“农作物”和“动物”两个类。每当时间流逝时,我都会检查我的一系列农田,每个农田都有农产品,并单独种植农作物。为此,我尝试识别农田中物体的类型。
Produce b = lands[i].getPlanted();
Produce* ptr = &b;
Crops* crops = dynamic_cast<Crops*>(ptr);
上面是我所做的,然后有一个if语句,如果crops != nullptr就会发生。尽管我知道 Farmland 数组(土地)中有农作物,并且 Produce 有一个虚拟函数,但这种说法并没有发生。 我对此很陌生,所以请友善。
编辑:我已更改 getPlanted() 以返回指向 planted 的指针,并将上面的代码更改为:
//Produce& b = lands[i].getPlanted();
Produce* ptr = lands[i].getPlanted();
Crops* crops = dynamic_cast<Crops*>(ptr);
但我仍然没有成功。如果种植了农作物,农作物应该是 nullptr,对吗?
我们需要在基类中添加确定派生的方法,然后在派生中重写它。
#include <memory>
#include <vector>
#include <iostream>
enum ProduceType{
animal,
crop
};
struct Produce{
virtual ProduceType get_type() const = 0;//this one
};
struct Animal final : public Produce {
ProduceType get_type() const override{
return ProduceType::animal;
}
void animal_thing() const {
std::cout << "animal thing\n";
}
};
struct Crop final : public Produce {
ProduceType get_type() const override
{
return ProduceType::crop;
}
void crop_thing() const {
std::cout << "crop thing\n";
}
};
int main ()
{
std::vector<std::shared_ptr<Produce>> land;
land.push_back(std::static_pointer_cast<Produce>(std::make_shared<Crop>()));
land.push_back(std::static_pointer_cast<Produce>(std::make_shared<Animal>()));
for(auto& ptr : land){
if(ptr->get_type() == ProduceType::crop){
std::static_pointer_cast<Crop>(ptr)->crop_thing();
}
if(ptr->get_type() == ProduceType::animal){
std::static_pointer_cast<Animal>(ptr)->animal_thing();
}
}
return 0;
}