以类型安全的方式将指针转换为指针

编程入门 行业动态 更新时间:2024-10-25 16:18:41
本文介绍了以类型安全的方式将指针转换为指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给出以下代码:

class Base { public: virtual ~Base() = default; }; class Derived : public Base { }; int main(void) { Derived d; Base* pb = &d; Base** ppb = &pb; Derived** ppd = ...; // Can this be defined in a type-safe manner? return 0; }

是否可以为分配给ppd的类型提供安全的表达式,而无需引入类型为Derived*的中间变量?

Is it possible to give a type-safe expression for the assignment to ppd, without introducing an intermediary variable of type Derived*?

推荐答案

AFAIK,并非没有声明指向d的Derived指针.指向d(pb)的Base指针已经通过抽象丢失了类型信息,没有不安全的强制转换就无法恢复.

AFAIK, not without declaring a Derived pointer to d. The Base pointer to d (pb) has already lost type information through abstraction, which cannot be recovered without a unsafe cast.

由于要声明指向Derived的指针,因此首先需要一个指向Derived的指针.例如:

Since you're declaring a pointer to a pointer to a Derived, you need a pointer to a Derived first. Eg:

Derived* pd = &d; Derived** ppd = &pd;

这两个定义都是类型安全的,在编译时检查.

Both of those definitions are type-safe, checked at compile time.

更多推荐

以类型安全的方式将指针转换为指针

本文发布于:2023-07-29 11:08:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1240157.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   转换为   类型   方式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!