gpt4 book ai didi

c++多重继承 - 编译器修改我的指针

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:47:14 24 4
gpt4 key购买 nike

如果我运行以下代码,我会打印出不同的地址。为什么?

class Base1 {
int x;
};

class Base2 {
int y;
};

class Derived : public Base1, public Base2 {

};

union U {
Base2* b;
Derived* d;
U(Base2* b2) : b(b) {}
};

int main()
{
Derived* d = new Derived;

cout << d << "\n";
cout << U(d).d << "\n";

return 0;
}

更有趣的是,如果你反复进出 union ,地址会一直递增 4,就像这样

int main()
{
Derived* d = new Derived;

cout << d << "\n";
d = U(d).d;
cout << d << "\n";
d = U(d).d;
cout << d << "\n";

return 0;
}

如果union这样修改,那么问题就解决了

union U {
void* v;
Base2* b;
Derived* d;
U(void* v) : v(v) {}
};

此外,如果任一基类为空,问题就会消失。这是编译器错误吗?我希望它别管我的指示。

最佳答案

If I run the following code, I get different addresses printed. Why?

因为 Base2 Derived 的子对象对象不在 Derived 的开头目的。所以地址不一样。当编译器从 Derived* 执行隐式转换时到 Base2* ,需要调整地址。

给定 Base1 的定义和 Base2类,都是 Derived 的子对象类不可能位于 Derived 的起始地址object - 该地址没有空间容纳两个子对象。

假设你有这段代码:

Derived* d = new Derived;

Base1* pb1 = d;
Base2* pb2 = d;

pb1怎么可能和 pb2指向同一个地址? pb1必须指向 Base1::x项目,和 pb2必须指向 Base2::y项(并且这些项必须不同)。

Even more fun is if you repeatedly go in and out of the union the address keeps incrementing by 4

因为您正在阅读 union 的 d成员写完b成员,这是未定义的行为(您实际上是在对 reinterpret_cast<Derived*>() 执行类似于 Base2* 的操作)。

I want it to leave my pointers the hell alone.

如果你想要 Base2* 就不行指针。多重继承使事情变得更加复杂 - 这就是为什么许多人建议除非绝对必要,否则避免使用它。

关于c++多重继承 - 编译器修改我的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12985299/

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