c++ - dynamic_cast (int* to int *) - 编译错误

标签 c++ dynamic-cast

对于下面的代码:

int i = 8;

int * p_i = &i;
int * p_j;

if (typeid(p_i) != typeid(p_j))
{
     p_j= dynamic_cast<int *>(p_i);
}

我得到以下编译错误:

error: cannot dynamic_cast ‘p_i’ (of type ‘int*’) to type ‘int*’ (target is not pointer or reference to class)

我错过了什么?

附言这是我得到的行为的简化示例(使用模板函数等),所以不要试图在此代码段中寻找任何目的。

更新: 由于这段代码是模板函数的一部分,我不知道我得到的是完整的类还是原语 - 这就是原因。

最佳答案

正如编译器错误指出的那样,您不能使用 dynamic_cast转换到int* .

使用 reinterpret_cast为此。

来自 C++11 标准:

5.2.7 Dynamic cast [expr.dynamic.cast]

1 The result of the expression dynamic_cast<T>(v) is the result of converting the expression v to type T. T shall be a pointer or reference to a complete class type, or “pointer to cv void.”

关于c++ - dynamic_cast (int* to int *) - 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39538625/

相关文章:

c++ - 删除数组的 SFML 析构函数问题

c++ - 使用 C header 时如何解决名称冲突?

c++ - dynamic_cast 在 linux 编译上的 "long distance"兄弟之间失败

C++ 动态转换失败/子对象被视为父对象

c++ - 错误 : cannot dynamic_cast . ..(目标不是指针或引用)

C++ 从非英文文件名和非英文文本中读取

c++ - 用自己的常量值定义变量的类型

c++将time_t转换为字符串并再次返回

c++ - 如何在我的 C++ 代码中避免 dynamic_cast?

c++ - 设计我的方式进入 dynamic_cast 我应该如何进行?