《C++面向对象》C++虚函数与多态性
2012-12-06 10:53
260 查看
虚函数与多态:目的是让父类指针可以调用子类的同名方法。
1.先看源码,test.cpp
2.g++ -o test test.cpp
3./test
看看不加virtual的结果:
看看加virtual的i结果:
1.先看源码,test.cpp
#include <iostream> using namespace std; namespace mytest{ class father{ public: virtual void common(){ //有无这个virtual,对引用(后边p1和p2影响) cout << "this is father!" <<endl; }; }; class son: public father{ public: void common(){ cout << "this is son!" <<endl; }; }; } using namespace mytest; int main(){ son *s = new son(); s->common(); father f; f.common(); father *p1 = s; p1->common(); father *p2 = &f; p2->common(); return 0; }
2.g++ -o test test.cpp
3./test
看看不加virtual的结果:
this is son! this is father! this is father! this is father!
看看加virtual的i结果:
this is son! this is father! this is son! this is father!
相关文章推荐
- C++程序设计学习之『多态性与虚函数』
- c++ 第五章 多态性和虚函数
- 一个C++继承、虚函数和多态性的实例代码
- c++ 虚函数和多态性
- 2013级C++第14周(春)项目——多态性、虚函数和抽象类 【项目1-动物这样叫】
- C++虚函数和多态性的关系【virtual】之一
- C++是如何利用虚函数实现多态性的?
- C++是如何利用虚函数实现多态性的?
- C++ 多态性 与 虚函数
- 2013级C++第14周(春)项目——多态性、虚函数和抽象类
- c++ 虚函数和多态性
- C/C++——多态性和虚函数
- C++之多态性与虚函数
- C++学习之路—多态性与虚函数(二)纯虚函数与抽象类
- C++多态性基本概念 包括虚函数和纯虚函数
- 【C++程序设计】-多态性和虚函数
- C/C++学习(1)面向对象的多态性问题、虚函数调用
- 读书笔记--C++程序设计(第2版)--12多态性与虚函数(虚析构函数,纯虚函数与抽象类)
- C++多态性及虚函数
- C++多态性,虚函数与纯虚函数