与强制类型转换指针相比,在dynamic_cast中使用强制类型转换引用
Change to use casting reference in dynamic_cast compared to casting pointer
我有很多if-else动态转换要向下转换,并执行特定的子类方法,如下所示。(我知道使用dynamic_cast可能被认为是设计上的错误。)
void cryout(const Animal* pAnimal)
{
if(!pAnimal){ return; }
...
if (auto pCat = dynamic_cast<const Cat*>(pAnimal))
{
pCat->meow();
}
else if (auto pDog = dynamic_cast<const Dog*>(pAnimal))
{
pDog->bark();
}
else
{
std::cerr << "No such animal.n" ;
}
}
然后我想更改为让参数通过引用传递,而不用担心空指针问题。
void cryout(const Animal& animal)
{
...
try
{
auto& cat = dynamic_cast<const Cat&>(animal);
cat.meow();
}
catch (std::bad_cast)
{
try
{
auto& dog = dynamic_cast<const Dog&>(animal);
dog.bark();
}
catch (std::bad_cast)
{
std::cerr << "No such animal.n";
}
}
}
但是这个改变涉及到当非猫动物对象传入时的堆栈展开。据我所知,堆栈展开可能会导致性能大幅下降。在我的情况下,这种参考方法实用吗?
BTW,是不是很奇怪,使"std::bad_cast异常"抛出在正常的工作流程?
给定很少的上下文,解决方案将是这样的:
#include <iostream>
#include <string>
struct Animal
{
virtual ~Animal() {}
};
struct Dog : Animal {
void bark() const { std::cout << "barkn"; }
};
struct Cat : Animal {
void meow() const { std::cout << "meown"; }
};
void cryout(const Animal& pAnimal)
{
if (auto pCat = dynamic_cast<const Cat*>(&pAnimal))
{
pCat->meow();
}
else if (auto pDog = dynamic_cast<const Dog*>(&pAnimal))
{
pDog->bark();
}
else
{
std::cerr << "No such animal.n" ;
}
}
int main()
{
Cat c;
cryout(c);
Dog d;
cryout(d);
}
但是除非你有没有选择 - Animal
应该有一个纯虚函数cryout()
在子类中重写…
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++中的双指针类型转换
- 逐位操作的隐式类型转换
- 模板中的类型转换
- 在 C++(和 C)中进行类型转换时明显不一致
- 字符类型转换不兼容
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- C++:用户定义的显式类型转换函数错误
- 将类指针类型转换为键时出错
- 通过引用传递参数时C++类型转换
- 在 C++ 中将一个模板类型的对象类型转换为另一个模板类型
- C++显式类型转换(C 样式强制转换)的强制表示法和static_cast的多种解释
- C++无效的函数类型转换
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 如何将Windows产品类型转换为名称?
- 通过构造函数方法输出的类到类类型转换是 5500 为什么不是 5555
- 事件系统:使用类型转换或联合进行继承
- 如何在参数中定义隐式类型转换的构造函数?
- 类模板实例化中的类型转换