c++ - 子类的两个派生类,但有两个返回类型
问题描述
我有一个超类(A)和两个子类(B,C)
A 中的抽象函数在 B 和 C 中有两种不同的返回类型!
我如何声明这些?
返回类型很重要
class A { //Super Class
public:
A();
virtual (some Type) QWERTY() = 0;
};
class B : public A { //Sub Class
public:
B();
double QWERTY();
};
class C : public A { //Sub Class
public:
C();
unsigned int QWERTY();
};
解决方案
我要用超类指针调用子类函数
由于每个子类中的函数不同,因此您必须从指向这些子类的指针访问它们。
这正是dynamic_cast<>
可以提供帮助的情况:当且仅当它恰好是正确的类型时,它可以有条件地将指针从基类转换为子类:
void foo(A* a_ptr) {
B* b_ptr = dynamic_cast<B*>(a_ptr);
C* c_ptr = dynamic_cast<C*>(a_ptr);
if(b_ptr) {
b_ptr->QWERTY();
}
if(c_ptr) {
c_ptr->QWERTY();
}
}
It's, however, worth mentioning that this is some pretty ugly code, and might be suitable to solve the quiz you are presenting us, but in a normal environment, there are some design reevaluation that would happen before going to implement things this way.
推荐阅读
- docker - Docker 上的 Nginx - proxy_pass to Directory 给出 404
- python - 通过 VBA 传递 Python 参数
- matlab - 通过方程 f(x,y) 在矩阵中找到等于数字 m 的两个元素
- node.js - Jest/Node Axios 测试抛出错误
- html - 如何使用 flexbox 之间的空间对齐多个跨度元素以垂直从同一位置开始
- javascript - 如何使用php编辑div的用户信息?
- reactjs - 反应 Axios 返回未定义
- powershell - PowerShell - 如何查看现有的 BalloonTip 通知
- python - 从包含多列的 csv 文件中汇总特定数据并在 python 字典中给出结果的方法
- node.js - 从expressJs中的表单数据请求中获取blob数据