c – 隐式铸造 – 使用铸造

前端之家收集整理的这篇文章主要介绍了c – 隐式铸造 – 使用铸造前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我有一个基类和子类以及一些多重继承:
class Child : public Base,public AnotherBase
{
};

函数foo(Base * b).我还实例化了一个Child * c.然后我打电话给foo(c).

编译器在此处进行隐式转换.但它需要一个C风格的演员表,一个static_cast< Base *>或者是其他东西?

解决方法

static_cast和C风格的强制转换是程序员明确要求进行类型转换的方式.您的示例是标准隐式转换,它是单独描述的,而不是根据显式转换.

您的示例称为派生到基本转换,并在标准中的[conv.ptr] / 2中定义:

N3337: A prvalue of type “pointer to cv D”,where D is a class type,can be converted to a prvalue of type “pointer to cv B”,where B is a base class of D. If B is an inaccessible or ambiguous base class of D,a program that necessitates this conversion is ill-formed. The result of the conversion is a pointer to the base class subobject of the derived class object. The null pointer value is converted to the null pointer value of the destination type.

换句话说,D *总是可以隐式转换为具有相同const和volitile资格的B *.

原文链接:https://www.f2er.com/c/118792.html

猜你在找的C&C++相关文章