当前位置:网站首页>非继承多态思路配合typeid实现不同参数的传递
非继承多态思路配合typeid实现不同参数的传递
2022-07-23 14:59:00 【本菜;】
首先说明我们的需求:
我们有A基类,B、C为A的派生类,A中有一个虚函数out无参数,B、C中有同名函数out,参数分别为int、char,我们需要将A指针指向B、C,且调用B、C中的out函数;
这个需求用继承多态我们是无法实现的,因为继承多态是通过积累的指针然后识别积累中的函数标识符,然后调用派生类具有系统标识符的函数,如果派生类中没有,那么就直接调用基类中的。这一过程,我们是通过基类中的函数标识符来调用函数的,因为B、C类中的out函数标识符不存在于A中,所以我们自然无法调用到了;
如下,利用非继承多态思路和typeid实现了:
#include<iostream>
#include<type_traits>
struct A {
virtual void out() {
std::cout << "None" << std::endl;
}
};
struct B :public A{
void out(double a) {
std::cout << a << std::endl;
}
};
struct C : public A {
void out(char a) {
std::cout << a << std::endl;
}
};
void func(A* Ptr) {
if (typeid(*Ptr) == typeid(B)) {
static_cast<B*>(Ptr)->out(3.1415926);
}
else if(typeid(*Ptr)== typeid(C)){
static_cast<C*>(Ptr)->out('T');
}
else if (typeid(*Ptr) == typeid(A)) {
static_cast<A*>(Ptr)->out();
}
}
int main() {
A* A_ = new A();
A* B_ = new B();
C* C_ = new C();
func(A_);
func(B_);
func(C_);
}运行结果:
None
3.14159
T
边栏推荐
- JS tool CECP
- [operation] Yan Yi (Internet new technology operation)
- [pytorch] basic use 7. GPU allocation
- 常见模拟电路设计 一(含仿真):方波、三角波、正弦波的互相发生「建议收藏」
- 食品安全|爱吃烟熏食品的注意了,这些知识你知道吗
- 【flask高级】从源码深入理解flask路由之endpoint
- 【redis入门系列】redis的数据类型及相关命令
- 使用 Preparedstatement 选择和显示记录的 JDBC 程序
- LeetCode_724_寻找数组的中心下标
- makefile 常用函数notdir、wildcard、patsubst
猜你喜欢
![[introduction series of redis] redis builds master-slave servers](/img/94/505ec8eeb9a10e09a00f61565cbaba.png)
[introduction series of redis] redis builds master-slave servers
![[MySQL Cluster fault recovery]](/img/bf/8073831d810293170c62356757c368.png)
[MySQL Cluster fault recovery]

面试官:MySQL 数据库查询慢,除了索引问题还可能是什么原因?

Food safety eating preserved eggs will lead poisoning? Don't worry about eating after knowing these points
一加OnePlus 10T的一系列规格在产品发布前被披露

工业物联网中的时序数据

为啥一问 JVM 就 懵B ???

Interviewer: what is the possible reason for the slow query of MySQL database besides the index problem?

Food safety chocolate is also true or false? How much do you know about it

卷积核越大性能越强?一文解读RepLKNet模型
随机推荐
Kv260 single board PS control setting IIC switch chip
Pymoo learning (4): multi criteria decision making
在 Kotlin 中使用 Flow Builder 创建流
单细胞论文记录(part19)--A comprehensive comparison on cell-type composition inference for ST data
Visual computer room management
Summary of stock historical data download interface (dynamic update)
深入理解机械系统的模态与振动
别再问我MySQL为啥没走索引?就这几种原因,全都告诉你
用pymysql封装项目通用的连接和查询
PPPoE协议讲解以及拨号过程Wireshark抓包解析
食品安全|火腿肠午餐肉,真有说的那么不堪?
蓝桥杯真题:卡片[通俗易懂]
使用 PreparedStatement 的 JDBC 程序示例
@Will multiple bean instances be created by multiple method calls of bean annotations
Redis分布式锁,没它真不行
KV260单板PS控制设置IIC开关芯片
Kubernetes kubelet manages pod core process
Unity production QR code scanning
Do you dare to use BigDecimal without mastering these pits?
Thread pool, who am I? Where am I?