gpt4 book ai didi

c++ - 什么是带扩展和不带扩展的强制转换

转载 作者:行者123 更新时间:2023-12-03 07:51:30 25 4
gpt4 key购买 nike

我读过Explicit type conversion (我的重点):

When the C-style cast expression is encountered, the compiler attemptsto interpret it as the following cast expressions, in this order:

  1. const_cast<target-type>(expression);
  2. static_cast<target-type>(expression), with extensions: pointer or reference to a derived class is additionally allowed to be cast topointer or reference to unambiguous base class (and vice versa) evenif the base class is inaccessible (that is, this cast ignores theprivate inheritance specifier). Same applies to casting pointer tomember to pointer to member of unambiguous non-virtual base;
  3. static_cast (with extensions) followed by const_cast;
  4. reinterpret_cast<target-type>(expression);
  5. reinterpret_cast followed by const_cast.

第 2 项和第 3 项中的“带有扩展名”是什么意思?如果可能的话,我想要一个带扩展名和不带扩展名(如果有)的转换示例。

最佳答案

这只是意味着扩展 static_cast 的功能,正如它所说:

pointer or reference to a derived class is additionally allowed to be cast to pointer or reference to unambiguous base class (and vice versa) even if the base class is inaccessible (that is, this cast ignores the private inheritance specifier). Same applies to casting pointer to member to pointer to member of unambiguous non-virtual base;

例如:

class A {};

class B : private A {};

你不能这样做:

B b;
A* a = static_cast<A*>(&b); // It's not allowed to convert to inaccessible base class A.

但是你可以:

A* a = (A*)(&b);

关于c++ - 什么是带扩展和不带扩展的强制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76982087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com