gpt4 book ai didi

c++ - 重载虚运算符 -> ()

转载 作者:可可西里 更新时间:2023-11-01 16:35:56 27 4
gpt4 key购买 nike

这只是一个实验代码。

struct B
{
virtual B* operator -> () { return this; }
void foo () {} // edit: intentionally NOT virtual
};

struct D : B
{
virtual D* operator -> () { return this; }
void foo () {}
};

int main ()
{
B &pB = *new D;
pB->foo(); // calls B::foo() !
}

我知道 operator 必须使用对象或引用来调用;因此,在上述情况下,引用 pB 是否仍然坚决指向 B 的对象?虽然不实用,但出于好奇,有没有办法通过 pB 调用 D::operator ->

最佳答案

我认为它调用D::operator->,但返回值被视为B*,所以B::foo() 正在被调用。

这是协变返回类型行为方式的产物。

关于c++ - 重载虚运算符 -> (),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6240890/

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