c++ - 抽象类访问其子类函数
问题描述
是否可以从作为父级的抽象类的指针访问子级的函数成员?这是抽象类
class Item {
public:
virtual double getTotalPrice() = 0;
};
这是子班
class Product : public Item {
protected:
string name;
public:
Product() {}
string getName() {}
double getTotalPrice() {}
};
是否可以在主驱动程序中从 Item 类的实例访问此 getName() 函数,因为我还想显示总价和产品名称?
解决方案
virtual
如果您应该能够delete
通过基类指针访问对象,则需要您的基类具有析构函数。- 也做
getName
virtual
。
class Item {
public:
virtual ~Item() = default;
virtual const string& getName() /* const */ = 0;
virtual double getTotalPrice() /* const */ = 0;
};
请注意,Product
不允许您更改的课程存在轻微缺陷。
- 它不会在应有的地方返回值。
- getter 成员函数不是
const
.
如果您不能自己做,建议进行一些更改:
class Product : public Item {
private: // prefer private member variables
string name;
public:
Product() = default;
const string& getName() const override { return name; }
double getTotalPrice() const override {
// why is this implemented here when there's no price to return?
return {};
}
};
推荐阅读
- python - 不能将 color_mode = 'grayscale' 与灰度 JPEG 一起使用
- ios - Flutter 无法捕获已终止 ios 应用程序的通知
- python - 为什么 ThreadPoolExecutor 忽略异常?
- json - 当我已经将该字段设置为可为空时。它没有优雅地解析信息。可能是什么问题?
- javascript - 如何将数组与使用本地存储的不同数组连接起来
- sql - Oracle SQL:基于行的重启顺序
- git - GitLab 中未显示的口音
- node.js - ReplicaSetNoPrimary MongooseServerSelectionError: getaddrinfo EAI_AGAIN mongodb-primary
- reactjs - 我在基于类的 reactjs 代码中有下面的照片上传器代码,我希望它在基于功能的工作代码中
- mysql - 用于选择性别的单选按钮。如何成功检索所选性别?