c++学习-虚函数
#include <iostream> using namespace std; class common{ public: virtual void hello(){cout<<"common hello"<<endl;} }; class a: public common{ public: //重写基类的虚函数后,本函数也是虚函数 可以省略 virtual virtual void hello(){cout<<"a hello"<<endl;} }; class b: public common{ public: void hello(){cout<<"b hello"<<endl;} }; int main() { //动态联编 在运行时才确定哪个指针确定哪个对象 //静态联编 在编译时就确定哪个指针确定哪个对象 速度快,浪费小 //虚函数实现了调用指向真实对象的方法 common *p = new a(); p->hello(); return 0; }
静态联编:在编译时就确定指针指向的类
#include <iostream> using namespace std; class common{ public: void hello(){cout<<"common hello"<<endl;} }; class a: public common{ public: void hello(){cout<<"a hello"<<endl;} }; class b: public common{ public: void hello(){cout<<"b hello"<<endl;} }; int main() { a i; common *p; //在编译时就确定指向 common 类,再改变也是无效的 p = &i; p->hello(); return 0; }
多态满足的条件:
#include <iostream> using namespace std; class father{ public: virtual void hello(){cout<<"father hello"<<endl;} }; class son: public father{ public: void hello(){cout<<"son hello"<<endl;} }; class doc: public father{ public: void hello(){cout<<"doc hello"<<endl;} }; void one(father one) { one.hello(); } void two(father *two) { two->hello(); } void three(father &three) { three.hello(); } int main() { /** 满足多态的条件: 1、继承 2、父类引用指向子类对象(指针或引用) 3、基类函数为虚函数 */ father *p=0; int choice; while(1){ bool quit = false; cout<<"0:退出,1:儿子, 2:女儿, 3:父亲"<<endl; cin>>choice; switch(choice) { case 0: quit=true; break; case 1: p = new son(); one(*p); break; case 2: p = new doc(); two(p); break; case 3: p=new father(); three(*p); } if(quit) { break; } } return 0; }
强制使用静态连接:
#include <iostream> using namespace std; class father{ public: virtual void hello(){cout<<"father hello"<<endl;} }; class son: public father{ public: void hello(){cout<<"son hello"<<endl;} }; class doc: public father{ public: void hello(){cout<<"doc hello"<<endl;} }; void one(father one) { one.hello(); } void two(father *two) { two->hello(); } void three(father &three) { three.hello(); } int main() { father *p=0; son a=son(); p=&a; p->father::hello();//强制使用静态连接 return 0; }
基类析构函数应声明为 virutal
#include <iostream> using namespace std; class father{ public: virtual void hello(){cout<<"father hello"<<endl;} father(){cout<<"father construct"<<endl;} //@warn virtual ~father(){cout<<"father destruct"<<endl;} //父类虚析构函数会自动调用子类虚析构函数 }; class son: public father{ public: void hello(){cout<<"son hello"<<endl;} son(){cout<<"son construct"<<endl;} ~son(){cout<<"son destruct"<<endl;} }; int main() { father *p = new son(); delete p; return 0; }