C++继承体系下函数调用辨析

本文最后更新于:2023年6月12日 下午

前情提要

Darli:如果我想用子类的实例调用父类的同名函数应该怎么写?

测试Code如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
using namespace std;
class A {
public:
void m(){
cout <<" this is A(m)" << endl;
}
virtual void func(){
cout <<" this is A" << endl;
}
};

class B: public A {
public:
void m(){
cout <<" this is B(m)" << endl;
}
virtual void func(){
cout <<" this is B" << endl;
}
};

int main()
{
A a;
B b;
A* c = new B();
a.func(); //this is A
b.func(); //this is B
b.A::func(); //this is A
c->func(); //this is B
c->A::func(); //this is A
((A)(*c)).func(); //this is A 生成A临时对象实例
c->m(); // this is A(m)
return 0;
}

Conclusion

Maybe:C++继承的同名函数可以分为虚函数重写和普通同名函数,而Java就默认重写了

C++体系中,有三种方法可以实现通过子类实例调用父类同名函数:

  • 域操作符(::) b.A::func(); c->A::func();
  • 将指针解引用并强转为父类,会产生一个临时父类对象实例,((A)(*c)).func();
  • 父类和子类中的普通同名函数(非virtual),酱紫的话 就失去了多态性 也就是不看实际类型 只看接收的类型,比如A* c = new B(); c->m();调用的就是A的m()

教学相长也 C++高深也


C++继承体系下函数调用辨析
https://mrbeancpp.github.io/2023/06/12/C-继承体系下函数调用辨析/
作者
MrBeanC
发布于
2023年6月12日
许可协议