gpt4 book ai didi

c++ - 隐式向上转换时如何确定偏移量?

转载 作者:行者123 更新时间:2023-11-30 03:44:19 24 4
gpt4 key购买 nike

#include <iostream>
using namespace std;

struct Left
{
char i = 'k';
};

struct Right
{
int a = 99;
};

struct Bottom : Left, Right
{};

int main()
{
Bottom b;

Left* l = &b;
cout << l->i;

Right* r = &b;
cout << r->a;

return 0;
}
// output
// k99

这是如何运作的?

如果Bottom的内存布局是:

Left
Right
Bottom

然后将b(即Bottom)切片到Left对象,应该没问题,但是当我切片时它怎么工作底部右侧对象?

为什么在这种情况下不需要静态转换?

最佳答案

由于编译器知道两个指针的类型,它可以应用必要的偏移量调整。如果打印出指针的值,您会发现它们有些不同。

关于c++ - 隐式向上转换时如何确定偏移量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35566932/

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