gpt4 book ai didi

C++ 多重继承和 void* 交叉委托(delegate)?

转载 作者:搜寻专家 更新时间:2023-10-31 02:23:24 25 4
gpt4 key购买 nike

class Base1
{
public:
virtual ~Base1(){}

virtual void whatever()
{
cout << "whatever" << endl;
}
};

class Base2
{
public:
virtual ~Base2(){}

virtual void aFunc(int i) = 0;
};

class A : public Base1, public Base2
{
public:
A()
{}
~A()
{}

virtual void aFunc(int i) final
{
cout << "func" << endl;
}
};

int main()
{
void* a;
a = new A();

(static_cast<Base2*>(a))->aFunc(0);

Base2* ptr = static_cast<Base2*>(a);
ptr->aFunc(0);

return 0;
}

此示例打印出“whatever”而不是“func”,如果我将带有 void* 的行更改为 A* 而不是打印出“func”。这是已知行为吗?我希望是这种情况,只是不知道为什么。

最佳答案

Is this a known behavior?

是的。如果您转换为 void* 然后返回相同类型,则行为定义明确。如果您转换回不同的类型,它是未定义的。

I would expect that's the case just don't know why.

不能保证基础子对象与完整对象具有相同的地址;事实上,如果有多个非空基类,那么至少有一个子对象必须位于不同的地址。因此,从 A*Base2* 的有效转换可能需要调整指针的值,而不仅仅是将其重新解释为不同的类型。转换为 void* 并返回无法进行该调整。

关于C++ 多重继承和 void* 交叉委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29350556/

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