gpt4 book ai didi

c++ - 继承类结构是什么样的?

转载 作者:行者123 更新时间:2023-11-28 03:18:00 25 4
gpt4 key购买 nike

全部:

我在研究C++的多态时,在这里找到了一个小例子:

#include <iostream>
using namespace std;
class Base{
public:
virtual void f(float x){cout<<"Base::f(float)"<<x<<endl;}
void g(float x){cout<<"Base::g(float)"<<x<<endl;}
void h(float x){cout<<"Base::h(float)"<<x<<endl;}
};

class Derived:public Base{
public:
virtual void f(float x){cout<<"Derived::f(float)"<<x<<endl;}
void g(int x){cout<<"Derived::g(int)"<<x<<endl;}
void h(float x){cout<<"Derived::h(float)"<<x<<endl;}
};
int main(void){
Derived d;
Base *pb=&d;
Derived *pd=&d;

//Good:behavior depends solely on type of the object
pb->f(3.14f); //Derived::f(float)3.14
pd->f(3.14f); //Derived::f(float)3.14

//Bad:behavior depends on type of the pointer
pb->g(3.14f); //Base::g(float)3.14
pd->g(3.14f); //Derived::g(int)3(surprise!)

//Bad:behavior depends on type of the pointer
pb->h(3.14f); //Base::h(float)3.14(surprise!)
pd->h(3.14f); //Derived::h(float)3.14


return 0;
}

在学习了虚函数之后,我想我明白了多态是如何工作的,但是这段代码中还有一些问题,我不想打扰别人解释这段代码是如何工作的,我只需要能告诉我细节的人在派生类内部(不需要太多细节,只显示方法函数指针(或索引)在 Vtable 中的排列方式和非虚拟继承的结构)。

来自 pb->h(3.14f);//Base::h(float)3.14(惊喜!)我想应该有几个 vtable,对吗?

谢谢!

最佳答案

您的代码中只有一个多态(虚拟)成员函数签名:f(float)。其他三个函数 g(float)g(int)h(float) 不是虚函数。由于您的“(惊讶!)”评论是在调用 g()h() 之后,我猜您对这些函数不是多态性感到惊讶,或者您实际上对非多态函数的行为感到惊讶。

如果您对 g()h() 不是多态感到惊讶,请注意 virtual 位于 each 多态函数。如果一个函数没有被声明为 virtual,只有当它与基类中的虚函数具有相同的签名时,它才会是多态的(这也意味着您的 virtual Derived是多余的,但我个人觉得这样多余的使用virtual是很好的风格)。因为 virtual 只出现在 f(float) 之前,所以只有 f(float) 是多态的。

由于 h() 不是多态的,因此通过基指针调用 h() 会调用 h() 的基版本也就不足为奇了

关于 g(),派生类中的名称隐藏基类中的任何相应名称,除非通过 using 声明返回。这就是为什么 pd->g(3.14f) 调用 Derived::g(int) 即使 Base::g(float) 是更好的比赛。 Base::g 不可见。如果将 using Base::g; 放在 Derived 类中,它将调用 g() 的浮点版本。 (注意 virtualg() 没有影响,因为 g(int)g(float) 是不同的函数签名——没有任何方法可以覆盖另一个。)

HTH

关于c++ - 继承类结构是什么样的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16243502/

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