c++ - 指向指针的指针的 reinterpret_cast
问题描述
如果我有一个指向指针的派生类指针Derived**
并希望将其转换为指向指针的基类指针Base**
,则 usingstatic_cast<Base**>(ppd)
无法编译,我被迫使用reinterpret_cast<Base**>
,这似乎工作正常。是否有一个原因?在进行这种 reinterpret_cast 时,我应该记住任何警告吗?
下面是我写的一段示例代码:
struct Base {
Base(int x0) : x(x0) {}
int x;
};
struct Derived : Base {
Derived(int x0, int y0): Base(x0), y(y0) {}
int y;
};
void foo(Base** ppb) {
*ppb = new Derived(5, 7);
}
void bar(Derived** ppd) {
foo(reinterpret_cast<Base**>(ppd));
}
int main() {
Base* pb = new Base(3);
cout << pb->x << endl;
delete pb;
foo(&pb);
cout << pb->x << ' ' << static_cast<Derived*>(pb)->y << endl;
delete pb;
Derived* pd = new Derived(2,4);
cout << pd->x << ' ' << pd->y << endl;
delete pd;
bar(&pd);
cout << pd->x << ' ' << pd->y << endl;
delete pd;
}
解决方案
您实际上根本不需要reinterpret_cast
:
void bar(Derived** ppd) {
Base *base;
foo(&base);
*ppd = static_cast<Derived*>(base);
}
推荐阅读
- laravel - Laravel sortBy 的运行速度比 orderBy 慢还是重?
- python - 使用 Python Client API 获取 Kubernetes 节点状态
- formio - 如何将formio离线插件集成到角度项目
- python - 用于从字符串中提取所有复杂日期格式的正则表达式
- google-apps-script - Google Form 使用工作表回答验证并根据它向用户发送电子邮件
- jenkins - 向代理添加更多“执行者”
- java - 通过 RFC 将 java 连接到 SAP(JCO) 时出现错误
- stack - 性能分析显示错误的调用图
- java - 如何在 Spring 中使用 HttpRequestInterceptor?
- bash - 用于从存储在配置文件中的类似 JSON 的格式中获取具有特定键的结构的脚本