C++ 中的Virtual关键字与多态
2016-08-01 00:00
169 查看
//
// [什么是Virtual Table]
//
在类成员函数前添加virtual关键字,该函数就是虚函数。
编译后,虚函数们保存在类中的一个数组里,叫做虚表(Virtual Table)
用含有虚表的类生成对象,对象的内存中就存在一个指向该类虚表的指针(虚指针)
这样使用虚函数时,即可通过对象中的虚指针来调用了
当子类继承存在虚表的父类时,父类的虚表也会被copy进子类中
当子类存在与父类的虚函数同名函数时,则子类中的该函数将会覆盖掉继承自父类的虚表中的同名函数,以此来实现对象的多态性
1:虚表编译后就被创建了
2:虚指针只有在对象创建时才被创建
//
// [开始测试]
//
// //[抽象类] //
// [什么是Virtual Table]
//
在类成员函数前添加virtual关键字,该函数就是虚函数。
编译后,虚函数们保存在类中的一个数组里,叫做虚表(Virtual Table)
用含有虚表的类生成对象,对象的内存中就存在一个指向该类虚表的指针(虚指针)
这样使用虚函数时,即可通过对象中的虚指针来调用了
当子类继承存在虚表的父类时,父类的虚表也会被copy进子类中
当子类存在与父类的虚函数同名函数时,则子类中的该函数将会覆盖掉继承自父类的虚表中的同名函数,以此来实现对象的多态性
1:虚表编译后就被创建了
2:虚指针只有在对象创建时才被创建
//
// [开始测试]
//
class Animal { public: Animal() { puts("Animal"); } virtual ~Animal() { puts("~Animal"); } virtual void eat() {puts("Animal::eat");} }; class Dog : public Animal { public: Dog() {puts("Dog");} ~Dog() {puts("~Dog");} void eat() {puts("Dog::eat");} }; void test() { Animal* a = new Dog; a->eat(); delete a; } /* 这里执行 a->eat(); 后,子类的eat()已经覆盖掉了虚表中继承自中父类的eat() 所以可以正常执行子类的eat() */ //结果:执行test后 //Animal //Dog //Dog::eat //~Dog //~Animal /* 这里如果基类Animal不加virtual的话 执行 a->eat(); 只是去执行一段Animal中的正常函数 */ //结果:执行test后 //Animal //Dog //Animal::eat //~Animal
// //[抽象类] //
class Animal { public: Animal() { puts("Animal"); } virtual ~Animal() { puts("~Animal"); } //这里定义eat()为纯虚函数 virtual xxx = 0 //带有纯虚函数的类为抽象类,无法被实例化 //继承类必须覆盖该函数的声明 //如果尝试实例化 new Animal; 编译器会提示错误 [“Animal”: 不能实例化抽象类] virtual void eat() = 0; }; //继承后仍为抽象类 class Dog : public Animal { public: Dog() {puts("Dog");} ~Dog() {puts("~Dog");} virtual void eat() =0; }; //博美犬继承并实现了抽象类Dog //可以被实例化 class Pomeranian : public Dog { public: Pomeranian () {puts("Pomeranian ");} ~Pomeranian () {puts("~Pomeranian ");} virtual void eat() {puts("Pomeranian :eat");} }; void test() { Animal* a = new Pomeranian; a->eat(); delete a; } //结果:test执行之后 //Animal //Dog //Pomeranian //Pomeranian:eat //~Pomeranian //~Dog //~Animal
相关文章推荐
- C++ 类的多态一(virtual关键字--构造函数深刻理解)
- 不使用virtual关键字实现C++多态
- [C/C++]关于C++类成员函数的重载、覆盖、隐藏与virtual关键字
- C++ virtual 关键字详解
- C++多态与继承--virtual
- 浅析c++中virtual关键字
- C++中的关键字之virtual
- [C++]virtual关键字:虚函数,虚继承和虚基类
- C++ virtual 关键字总结
- C#多态;父类引用指向子类对象;new和override的区别;new、abstract、virtual、override,sealed关键字区别和使用代码示例;c#类的初始化顺序
- 深入理解c++中virtual关键字
- 浅析c++中virtual关键字
- 【温故知新C/C++】virtual(多态,覆盖,隐藏)||strtok||strtod||strtol||strrchr||fgets
- 【C++面向对象】类继承、多态与virtual成员
- virtual关键字与多态
- 20140729 while((*pa++=*pb++)!='\0') 合并数组代码 C++类型转换关键字 封装 多态 继承
- virtual是c++中的关键字
- C++、C#中 abstract 与 virtual关键字的区别联系
- C++的多态性只能通过virtual关键字实现
- 多态时最好将基类的析构函数设为virtual、 C++中两个类相互包含引用问题 (转载)