static_cast和引用指针 [英] static_cast and reference to pointers

查看:487
本文介绍了static_cast和引用指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉我为什么这不编译:

Can anyone tell me why this doesn't compile:

struct A { };
struct B : public A { };

int main()
{
  B b;
  A* a = &b;
  B* &b1 = static_cast<B*&>(a);
  return 0;
}

现在,如果将静态转型替换为:

Now, if you replace the static cast with:

B* b1 = static_cast<B*>(a);

那么它会编译。

strong> Edit:显然,编译器将 A * B * 视为独立类型,否则这将工作。

It is obvious that the compiler treats A* and B* as independent types, otherwise this would work. The question is more about why is that desirable?

推荐答案

B 是源自 A ,但 B * 不是从 A *
指向 B 的指针不是指向 A 的指针,它只能是
转换为一。但是类型保持不变(并且
转换可以,并且经常会改变
指针的值)。 B *& 只能指向 B * ,而不能指向任何其他
指针类型。

B is derived from A, but B* isn't derived from A*. A pointer to a B is not a pointer to an A, it can only be converted to one. But the types remain distinct (and the conversion can, and often will, change the value of the pointer). A B*& can only refer to a B*, not to any other pointer type.

这篇关于static_cast和引用指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆