gpt4 book ai didi

C++运算符重载和多态性

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

多态性和运算符重载混合在一起了吗?没有指针就无法实现多态性,如 this answer 中所述。而且你不能像解释的那样用指针重载运算符 here .
所以真的没有办法做到这一点,对吧?

最佳答案

是的。您没有正确阅读答案。

这是一个简短的演示:

#include <iostream>
using namespace std;

struct X
{
int value;
virtual void operator += (int x)
{
value += x;
}
};

struct Y : X
{
virtual void operator += (int x)
{
value *= x;
}
};

void do_stuff(X& x)
{
x += 10;
cout << "Final value " << x.value << endl;
}

int main()
{
X x;
x.value = 10;
Y y;
y.value = 10;
do_stuff(x);
do_stuff(y);

return 0;
}

我并不是在暗示这是个好主意,或者它很实用。这只是可能的。

关于C++运算符重载和多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11258617/

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