gpt4 book ai didi

C++:在派生类的对象上调用函数的函数调用优先级规则?

转载 作者:行者123 更新时间:2023-12-05 01:49:56 25 4
gpt4 key购买 nike

我有一个 class Iterator ,为此我定义了各种用于相等性测试的运算符重载( <<=>>===!= )作为友元函数。原型(prototype)示例:

friend bool operator<(const Iterator &A, const Iterator &B);

class RevIterator (实际上)继承自 Iterator .自然地,我不得不重载运算符 < , <= , >>=对于这个类(作为 friend 再次发挥作用)。原型(prototype)示例:

friend bool operator<(const RevIterator &A, const RevIterator &B);

我还有一个 class ConstIterator它(实际上)继承自 Iterator ,我没有为它定义更多的运算符重载(它们的行为方式与 Iterator 相同)。

最后,我有一个 class ConstRevIterator继承自 RevIteratorConstIterator ,我没有为其定义任何运算符重载。

可视类层次结构:

class Iterator {};
class RevIterator : virtual public Iterator {};
class ConstIterator : virtual public Iterator {};
class ConstRevIterator : public RevIterator, public ConstIterator {};

我的假设是对于运算符 < ,例如,对两个 ConstRevIterator 进行操作s,父类之一可用的函数,RevIterator (上面的第二个函数原型(prototype))将被调用,而不是祖父类的函数,Iterator (上面的第一个函数原型(prototype))。

总而言之,当父类和祖父类有可用的函数时,在引用“孙子”对象时调用哪个函数的规则是什么?

最佳答案

您的假设似乎是正确的。您可以在此处找到重载决议规则 https://en.cppreference.com/w/cpp/language/overload_resolution

这是关于你的问题的部分:

  1. If Mid is derived (directly or indirectly) from Base, and Derived is derived (directly or indirectly) from Mid

a) Derived* to Mid* is better than Derived* to Base*

b) Derived to Mid& or Mid&& is better than Derived to Base& or Base&&

c) Base::* to Mid::* is better than Base::* to Derived::*

d) Derived to Mid is better than Derived to Base

e) Mid* to Base* is better than Derived* to Base*

f) Mid to Base& or Base&& is better than Derived to Base& or Base&&

g) Mid::* to Derived::* is better than Base::* to Derived::*

h) Mid to Base is better than Derived to Base

我还制作了一些代码来验证它: https://godbolt.org/z/bc47dzxvY

关于C++:在派生类的对象上调用函数的函数调用优先级规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73602071/

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