最近确实遇到一些被搞懵的多态题
后期遇到再更新。。。
1、普通的多态
根据指针指向的实例化对象,确定虚函数的重写情况--基本的最扎实的多态。
2. 嵌套调用函数的多态
基类函数最开始初始化的时候,还没有派生类,派生类的虚函数重写没有发生作用哦。
(隐藏组合类的构造函数的初始化顺序:基类构造函数--派生类构造函数)
class Base {
public:
Base() {
echo();
}
virtual void echo() {
printf("Base");
}
};
class Derived:public Base {
public:
Derived() {
echo();
}
virtual void echo() {
printf("Derived");
}
};
int main() {
Base* base = new Derived();
base->echo();
return 0;
}
运行结果:
Base
Derived
Derived
3. 涉及指针类型转换的多态
看准指针指向的实例化对象,如果该指针来源于已经有指向的指针的实例化,则关注该来源的指针最初是哪个对象的实例化。
#include <iostream>
using namespace std;
class Base {
public:
void virtual Func() {
cout << "Base" << endl;
}
};
class Derived : public Base {
public:
void virtual Func() {
cout << "Derived " << endl;
}
};
int main() {
Base* pBase = new Base();
pBase->Func();
Derived* pDerived = (Derived*)pBase;
pDerived->Func();
delete pBase;
pDerived = new Derived();
pBase = pDerived;
pBase->Func();
delete pDerived;
return 0;
}
运行结果:
Base Base Derived