当前位置:网站首页>非继承多态思路配合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
边栏推荐
- Opencv finding the intersection of two regions
- Can debug/release versions of dynamic library *.dll files be mixed (cross used)?
- Mysql: MySQL problem that is not a MySQL problem
- What about the new retail e-commerce platform? Can we realize the digital transformation of traditional retail enterprises?
- Kubernetes Kubelet管理pod核心流程
- Date formatting
- Aike AI frontier promotion (7.23)
- sns_sensor_instance_api
- 【flask高级】从源码深入理解flask路由之endpoint
- Agile testing practice in large-scale teams
猜你喜欢

Food safety | eight things you must know when choosing probiotic products

你真的了解Redis的持久化机制吗?

食品安全|火腿肠午餐肉,真有说的那么不堪?

Visualization of network infrastructure

@Will multiple bean instances be created by multiple method calls of bean annotations

职场3道坎:年薪30万、50万、100万

Software configuration | Anaconda download, installation, environment configuration and uninstall

sns_ sensor_ instance_ api

Detailed explanation of SQL bool blind note and time blind note

深入理解机械系统的模态与振动
随机推荐
使用 Preparedstatement 选择和显示记录的 JDBC 程序
Explication détaillée de l'injection aveugle d'erreur SQL
深入理解机械系统的模态与振动
LeetCode_ 724_ Find the central subscript of the array
Summary of stock historical data download interface (dynamic update)
Kubernetes 聚焦Kubelet职责
项目中遇到的问题及解决
PHP 中 try-catch 和 if-else 语句的区别
转账业务追加日志(事务的传播行为).
基于C语言开发的控制台计算器
Food safety | ham sausage lunch meat, is it really so unbearable?
阿里二面:什么是CAS?
[ pytorch ] 基本使用丨7. GPU分配丨
Interviewer: how to use redis to realize distributed locks?
KV260单板PS控制设置IIC开关芯片
深拷贝deepClone的实现
Major upgrade of openim - group chat reading diffusion model release group management function upgrade
可视化机房管理
JS tool CECP
食品安全|喝鲜奶可能感染结核病?带你了解什么是牛奶灭菌