gpt4 book ai didi

c++ - 在 C++ 中使用 'static_cast' 向下转换

转载 作者:IT老高 更新时间:2023-10-28 22:33:13 33 4
gpt4 key购买 nike

考虑:

class base
{
base();
virtual void func();
}

class derived : public base
{
derived();
void func();
void func_d();
int a;
}


main
{
base *b = new base();
sizeof(*b); // Gives 4.
derived * d = static_cast<derived*>(b);
sizeof(*d); // Gives 8- means whole derived obj size..why?
d->func_d();
}

在上面的代码中,我将指向基对象的基指针向下转换为派生类指针。我想知道派生指针如何拥有整个派生类对象。我可以调用派生类函数(仅在派生类中声明)。我在这里没有得到这个概念。

最佳答案

使用 static_cast 将对象转换为它实际上没有的类型会产生 未定义的行为。 UB的症状差异很大。没有什么说 UB 不能让派生的成员函数被成功调用(但没有什么可以保证它会,所以不要指望它)。

这是使用 static_cast 进行向下转换的规则,可在 C++ 标准 (C++0x) 的第 5.2.9 节 ([expr.static.cast]) 中找到措辞):

A prvalue of type "pointer to cv1 B", where B is a class type, can be converted to a prvalue of type "pointer to cv2 D", where D is a class derived from B, if a valid standard conversion from "pointer to D" to "pointer to B" exists, cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is neither a virtual base class of D nor a base class of a virtual base class of D. The null pointer value is converted to the null pointer value of the destination type. If the prvalue of type "pointer to cv1 B" points to a B that is actually a subobject of an object of type D, the resulting pointer points to the enclosing object of type D. Otherwise, the result of the cast is undefined.

关于c++ - 在 C++ 中使用 'static_cast' 向下转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6322949/

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