计算具有给定属性的不同对象的列表中的元素
Counting elements in a list with different objects given a property
所以我有这两个类,我想计算在我的列表中有玫瑰种类的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> 相关文章:
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- 如何在不销毁对象的情况下返回对象列表
- 如何使用Q_PROPERTY公开自定义对象列表
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- c++ 循环访问对象列表并删除对象
- 循环访问对象列表 c++
- Cython正在获取C++对象列表的长度
- 如何在屏幕上显示对象列表?
- Strcmp 类行为应用于C++中的对象列表
- 如何迭代指针指向的对象列表?
- C++对象列表数组
- 使用BOOST :: PYTHON返回裸露的类对象列表,这些对象是不可复制的
- 返回对象列表
- C 链接对象列表
- 使用for_each从对象列表中调用打印功能
- 从对象列表中获取具有特定成员值的所有对象
- 按指针列出的 C++ 对象列表
- 子类对象列表重新解释为基类对象列表?(C++11).
- 在C++中的混合对象列表中使用相同的方法
- Python:我们应该如何编写一个函数来返回对象/列表和布尔标志