【发布时间】:2020-08-30 02:57:09
【问题描述】:
我有一个名为 Goods 的抽象类。 基于这个类,我派生出其他类,例如 Potatoes、Toys、Wine。
Beer
b1(/*price*/ 4,
/*quantity*/ 1000,
/*type*/ "red",
/*name*/ "Skolls"),
b2(/*price*/ 3.5,
/*quantity*/ 1000,
/*type*/ "blonde",
/*name*/ "Braun");
Potatoes
p1(/*price*/ 2,
/*quantity*/ 1000,
/*type*/ "red"),
p2(/*price*/ 2,
/*quantity*/ 1000,
/*type*/ "white");
Wine
w1(/*price*/ 4.5,
/*quantity*/ 1000,
/*name*/ "Chavignon",
/*origin*/ "France",
/*year*/ 2000),
Market market;
market.Consumer.push_back(&b1);
market.Consumer.push_back(&b2);
market.Consumer.push_back(&p1);
market.Consumer.push_back(&p2);
market.Consumer.push_back(&w1);
我将它们添加到一个名为 Consumer 的向量中,声明如下:
std::vector<Goods*> Consumer
我想不通的是如何在这样的 for 语句中将每个元素从 Consumer 转换为其 Derived 等效项,以便我可以基于派生类应用一些特定方法.
for (int i = 0; i < Consumer.size(); i++) {
Wine* Consumer[i] = static_cast<Goods*>(Consumer[i]);
当我尝试按上述方式进行操作时,我收到关于 i 值的错误:“表达式必须具有常量值”
商品.H
#pragma once
#include <iostream>
#include <string>
#include <vector>
//Base class
class Goods
{
protected:
double Price;
double Quantity;
public:
virtual void setprice(double prc) = 0;
virtual double getprice() const = 0;
virtual void setquantity(double qty) = 0;
virtual double getquantity() const = 0;
virtual std::string getID() const = 0;
virtual void print() = 0;
Goods();
Goods(double prc, double qty);
~Goods();
};
【问题讨论】:
-
使用多态来实现你的目标。
-
@ElvisOric,我已经有虚拟(纯)函数,(在我的示例中)是每个派生类的 getter 和 setter。您的意思是添加其他我稍后将在派生类中覆盖的虚函数?
-
好吧,你想做什么,在你的派生类中重写那个操作。
-
回复:“我已经有虚拟 ... 函数”——不在您显示的代码中。没有人能从代码片段中给你有用的答案。
-
@PeteBecker 这是一段很长的代码,有很多标题和其他技术细节。我试图尽可能简洁明了。
标签: c++ oop casting polymorphism