当基类指针传递参数时,检查孩子的类型
checking type of child when argument is passed by base class pointer
我有一个基础B
及其2个衍生(D1
,D2
)类,看起来像
struct B
{
virtual B* DoSomething()=0;
};
struct D1:public B
{
B* DoSomething()
{
// D1 does something
return pD1;
}
};
struct D2:public B
{
B* DoSomething()
{
// D2 does something
return pD2;
}
};
现在我有一个函数
void Init(B*pB)
{
if(pB is D1)
{
D1* pD1=down_cast(pB);
pD1->MethodD1();
}
else if(pB is D2)
{
D2* pD2=down_cast(pB);
pD2->MethodD2();
}
else
{
//do something else
}
}
我不想在Init()
中检查类型,但不知道我可以做什么。
真的应该做
struct B
{
virtual void Init();
virtual B* DoSomething()=0;
};
struct D1:public B
{
B* DoSomething()
{
// D1 does something
return pD1;
}
void Init()
{
MethodD1();
}
};
struct D2:public B
{
B* DoSomething()
{
// D2 does something
return pD2;
}
void Init()
{
MethodD2();
}
};
和您的主代码
void Init(B*pB)
{
pB->Init();
}
那就是封装,继承,虚拟方法等的全部点。
这是您的 Init()
方法不在伪代码中:
void Init(B*pB)
{
if(D1 *pD1 = dynamic_cast<D1*>(pB))
{
pD1->MethodD1();
}
else if(D2 *pD2 = dynamic_cast<D2*>(pB))
{
pD2->MethodD2();
}
else
{
//do something else
}
}
您可以看到Dynamic_cast返回nullptr
如果派生类的类型不是您要铸造的类。
您也可以使用引用来执行此操作,在这种情况下,Dynamic_cast会返回一个例外,如果类型不是您要铸造的类型,因此,由于异常处理不是免费的,因此最好将指针用于动态铸造目的。请注意,这是运行时检查,而不是编译时间检查。
相关文章:
- valgrind-hellgrind与泄漏检查的结果不同
- C++模板来检查友元函数的存在
- 检查输入是否不是整数或数字
- 试图让变量检查数组中的某些内容
- 检查值是否在集合p1和p2中,但不在p3中
- C++概念:如何使用'concept'检查模板化结构的属性?
- 概念TS检查忽略私有访问修饰符
- 检查 std::shared_ptr<> 的当前底层类型是否为 T
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- 如何在C++中检查2D数组中负值的输入验证
- C++:正在检查LinkedList中的回文-递归方法-错误
- 使用for循环检查数组中的重复项
- 如何检查一个c++字符串中有多少相同的字符/数字
- 检查不带转换的扫描格式
- 如何检查线程是否锁定
- 清除前检查矢量
- 如何处理来自核心指南检查器的关于gsl::at的静态分析警告
- C++LDAP检查用户是否是特定组的成员
- 当基类指针传递参数时,检查孩子的类型
- QTreeView:检查父母后如何检查孩子