计算具有给定属性的不同对象的列表中的元素

Counting elements in a list with different objects given a property

本文关键字:对象 列表 元素 计算 属性      更新时间:2023-10-16

所以我有这两个类,我想计算在我的列表中有玫瑰种类的FlowersGarden对象的数量:

class Garden {
private:
    string owner;
    double lenght, width;
public:
    Garden(string ow, double l, double w) {
        this->ownder = ow;
        this->lenght = l;
        this->width = w;
}
class FlowersGarden: public Garden {
private:
    string species;
public:
    FlowersGarden(string ow, double l, double w, string sp):Garden(ow, l, w) {
        this->species = sp;
}
    string GetSpecies()const {return species;};
};

main.cpp

Graden** list;
list = new Garden* [5];
list[0] = new Garden("asdas", 54, 57);
list[1] = new FlowersGarden("tyyty", 98, 87, "rose");
list[2] = new FlowersGarden("asdasd", 578, 212, "sadas");
list[3] = new Garden("uyiyui", 687, 212); 
int count = 0;
for (int i = 0; i < 4; i++)
    if(dynamic_cast<FlowersGarden*>(list[i]))
        if(list[i]->GetSpecies() == "rose")
           count++;

这是我唯一能想到的解决这个问题,我得到这个错误:"类'花园'没有名为'GetSpecies'的成员",我知道为什么,但我不知道另一种方式。

if(dynamic_cast<FlowersGarden*>(list[i]))

该保护正确地验证了派生类型为FlowerGarden类型。但是,list[0]->GetSpecies仍然使用Garden类型的指针,该指针不具有您试图使用的功能。

您只需要保留强制转换的结果并使用它来调用函数。例如:

if (FlowersGarden* result = dynamic_cast<FlowersGarden*>(list[i]))
{
    if (result->GetSpecies() == "rose")
    {
        ...
    }
}

注:正如@max66在评论中指出的。你发布的代码似乎有一个拼写错误的功能FlowersGarden类,GetSpecie vs GetSpecies


编辑:

我不确定你最终想做什么(关于你的类层次结构),但我认为指出virtual函数是合适的。如果你在一个情况下,有一个函数是适用于所有派生类,那么你应该把它添加到基类,并使其virtual。通过这样做,执行dynamic_cast是不必要的,并且动态调度将在通过基类指针调用时调用派生类实现。

例如:

#include <iostream>
#include <memory>
class Base
{
public:
    virtual ~Base() {}
    virtual void print() const = 0; // Pure abstract function
};
class Derived : public Base
{
public:
    virtual void print() const override { std::cout << "Derivedn"; }
};
int main()
{
    std::unique_ptr<Base> base = std::make_unique<Derived>();
    base->print();
    return 0;
}
输出:

Derived
<<p> 生活例子/kbd>