我想list<abstract>
使用 for 循环遍历抽象类的列表。
这是我的代码:
class Component {
protected:
string name;
int price;
public:
Component(string name, int price): name(name), price(price){};
virtual int getPrice() =0;
};
class Composite : public Component {
list<Component> components;
public:
int getPrice() {
for(Component comp : components) {
return comp.getPrice();
}
}
};
class Leaf : public Component {
public:
int getPrice() {
return price;
}
};
但是我得到一个错误;无法分配抽象类型“组件”的对象。这个错误是有道理的,因为抽象类型不能被实例化。
您的代码有一些问题:
你声明virtual int getPrice() = 0;
,这使你的Component
纯虚拟 -> 你不能实例化它的一个对象 ->list<Component> components;
出现没有意义。请考虑使用list<Component*>
(或智能指针)代替!
基于范围的 for 循环:
for(Component comp : components) {
return comp.getPrice();
}
假设你已经更新了你的列表,list<Component*>
那么 for 循环可能是:
for(auto& comp : components) {
return comp->getPrice();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句