1. C++在内存布局以及时间上的主要负担是由virtual引起的,包括
2. C++指针会教会编辑器如何解释特定地址的内容及大小
3. C++通过指针与引用实现多态
class BaseClass{ public: BaseClass(int elem): m_elem(elem){ } virtual void Print(){ cout << "Base Class: " << m_elem << endl; } public: int m_elem; }; class DeviceClass: public BaseClass{ public: DeviceClass(int elem): BaseClass(elem) { } virtual void Print(){ cout << "Device Class: " << m_elem << endl; } };
int main() { cout << "BaseClass And Device Class" << endl; BaseClass baseClass(4); baseClass.Print(); DeviceClass deviceClass(5); deviceClass.Print(); cout << "Polymorphism With Reference" << endl; BaseClass& rBaseClass = deviceClass; rBaseClass.Print(); cout << "Polymorphism With Point" << endl; BaseClass* pstBaseClass = &deviceClass; pstBaseClass->Print(); }
执行结果
BaseClass And Device Class Base Class: 4 Device Class: 5 Polymorphism With Reference Device Class: 5 Polymorphism With Point Device Class: 5
使用子类对象初始化父类指针,调用虚函数时,虚表对应位置查找到的函数为子类函数,实现运行期多态
使用子类对象初始化父类引用,会出现对象切割行为,但是调用虚函数是,虚表对应位置查找到的函数为子类函数,实现运行期多态