C++ 使用给定属性的不同对象计算列表中的元素

C++ 使用给定属性的不同对象计算列表中的元素,c++,oop,c++11,inheritance,dynamic-cast,C++,Oop,C++11,Inheritance,Dynamic Cast,所以我得到了这两个类,我想计算列表中有玫瑰的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; }

所以我得到了这两个类,我想计算列表中有玫瑰的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++;
Graden**列表;
列表=新花园*[5];
列表[0]=新花园(“asdas”,54,57);
列表[1]=新花花园(“tyyty”,98,87,“rose”);
列表[2]=新花花园(“asdasd”,578212,“sadas”);
清单[3]=新花园(“乌依依依”,687212);
整数计数=0;
对于(int i=0;i<4;i++)
if(动态_cast(列表[i]))
如果(列表[i]->GetSpecies()=“rose”)
计数++;
这是我唯一能想到的解决这个问题的方法,我得到了一个错误:“类‘Garden’没有名为‘GetSpecies’的成员”,我明白了原因,但我不知道另一种方法

if(动态演员表[i])

此防护正确验证派生类型是否为类型
FlowerGarden
。但是,
list[0]->GetSpecies
仍在使用类型为
Garden
的指针,该指针没有您尝试使用的函数

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

if (FlowersGarden* result = dynamic_cast<FlowersGarden*>(list[i]))
{
    if (result->GetSpecies() == "rose")
    {
        ...
    }
}
#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 << "Derived\n"; }
};

int main()
{
    std::unique_ptr<Base> base = std::make_unique<Derived>();
    base->print();

    return 0;
}
输出:

Derived

C++中使用C语法,它看起来像.<代码> GET物种()/<代码>而不是<代码> GESPECIEE()>代码>,但这不是造成问题的原因。不要复制你的代码代码,你可以使用
std::string
,但既不能使用
std::vector
也不能使用
std::unique\u ptr
。。。