为了定义一个基类,然后派生出几个子类分别对应不同的情况,在基类中写好函数接口,之后可以使用基类作为接口来对几种不同子类的情况进行操作.
为了方便解释,我写一个小的程序验证一下相关的想法:
ABase
→
\rightarrow
→ A
→
\rightarrow
→ A1
ABase 为基类,有纯虚函数fun();A为其派生类,覆盖重写了虚函数,A1为A的派生类,继续重写了函数
#include <iostream>
using namespace std;
class ABase{
public:
virtual void fun() const = 0;
};
class A : public ABase{
public:
A(){
fun();
}
virtual void fun() const {
cout << "now, it's A" << endl;
}
};
class A1 : public A{
public:
A1(){
fun();
}
virtual void fun() const {
cout << "now, it's A1" << endl;
}
};
void print_Aclass(ABase * a){
cout << "print_Aclass:" << endl;
a->fun();
}
void print_Aclass_1(A * a){
cout << "print_Aclass_1:" << endl;
a->fun();
}
int main(){
cout << "for the A:" << endl;
A *a_ = new A();
print_Aclass(a_);
cout << endl << "for the A1:" << endl;
A1 *a1_ = new A1();
print_Aclass(a1_);
cout << endl << "the second fun: " << endl;
print_Aclass_1(a1_);
return 1;
}
结果为:
for the A:
now, it's A
print_Aclass:
now, it's A
for the A1:
now, it's A
now, it's A1
print_Aclass:
now, it's A1
the second fun:
print_Aclass_1:
now, it's A1
可以看到几点:
- 首先构造A1时先构造它的基类A,所有A中的构造函数也要被调用,而且是先于A1的构造函数被调用
- 调用函数print_Aclass时传入的是ABase的继承类,在执行参数类对象里面的函数fun时,不管其基类有没有声明fun的内容(声明:print_Aclass(a1_); 未声明: print_Aclass_1(a1_))调用的是子类复写的fun函数
讲到这里,继续看一下如果子类没有复写,是什么效果
class A2 : public A{
public:
A2(){
fun();
}
};
//main
cout << endl << "for the A2:" << endl;
A2 *a2 = new A2();
print_Aclass(a2);
结果:
for the A2:
now, it's A
now, it's A
print_Aclass:
now, it's A
可以看到,函数会调用距离子类最近的实现了该函数的父类的函数.因为,如果没有override的话,默认为和其父类相同,因此实际上还是调用的该类中的函数fun