下面做一个简单的实验,看看c++与c#在重写虚函数时候调用基类的虚函数的时候的情况,大家自己可以对比一下c#.测试代码:
1: #include
2: using namespace std;
3:
4: class Base
5: {
6: public:
7: virtual void Func() { cout "Hello Earth"
8: };
9:
10: class Derived : public Base
11: {
12: public:
13: virtual void Func() { cout "Hello World"
14: };
15:
16: int main()
17: {
18: Base* p1 = new Base();
19: p1->Func();
20:
21: Base* p2 = new Derived();
22: p2->Func();
23: }
输出:
Hello Earth
Hello World
而在将Base的Func()改为纯虚函数之后,在Base* p1 = new Base()这句话上出现编译错误,提示不能实例化抽象类. 而对于p2的调用时正常的 下面继续深入我们的实验,三个类依次继承,爷爷类具有一个纯虚函数,爸爸类什么都不写,儿子类重写该函数,都使用virtual public继承:
1: #include
2: using namespace std;
3:
4: class Base
5: {
6: public:
7: virtual void Func() = 0 ;
8: };
9:
10: class Derived : virtual public Base
11: {
12:
13: };
14:
15: class DerivedDerived : virtual public Derived
16: {
17: public:
18: virtual void Func() { cout "Hello World"
19: };
20:
21: int main()
22: {
23: Base* p1 = new DerivedDerived();
24: Derived* p2 = new DerivedDerived();
25:
26: p1->Func();
27: p2->Func();
28: }
输出结果都是"Hello World"