cast const Class using dynamic_cast(使用 dynamic_cast 强制转换 const 类)
问题描述
我想投这个:
class Base
{
public:
virtual ~Base(){};
};
class Der : public Base {};
int main()
{
const Base* base = new Der;
Der* der = dynamic_cast<Der*>(base); // Error
return 0;
}
我该怎么办?我试图输入: const Der* der = dynamic_cast 来维护 const 但这不起作用.
What should I do?
I tried to put: const Der* der = dynamic_cast<Der*>(base); to mantain the const but this doesn't work.
推荐答案
试试这个:
const Der* der = dynamic_cast<const Der*>(base);
dynamic_cast 无法删除 const 限定符.您可以使用 const_cast 单独抛弃 const,但在大多数情况下这通常是个坏主意.就此而言,如果你发现自己在使用 dynamic_cast,这通常表明有更好的方法来做你想做的事情.这并不总是错误的,但可以将其视为您正在以艰难的方式做事的警告信号.
dynamic_cast doesn't have the ability to remove a const qualifier. You can cast away const separately using a const_cast, but it's generally a bad idea in most situations. For that matter, if you catch yourself using dynamic_cast, it's usually a sign that there is a better way to do what you are trying to do. It's not always wrong, but think of it as a warning sign that you are doing things the hard way.
这篇关于使用 dynamic_cast 强制转换 const 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 dynamic_cast 强制转换 const 类
- 将 hdc 内容复制到位图 2022-09-04
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- DoEvents 等效于 C++? 2021-01-01
- GDB 不显示函数名 2022-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- XML Schema 到 C++ 类 2022-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
