虚函数

虚函数

代码以下定义:ios

// test1107.cpp : 定义控制台应用程序的入口点。 //  #include "stdafx.h" #include <iostream> #include <vector>
using namespace std; class father{ public: int f_age; std::string f_name; father(int a = 1,std::string n = ""):f_age(a),f_name(n){} virtual int get_age(){return f_age;} }; class son : public father{ public: int s_age; std::string s_name; son(int a = 0,std::string n = ""):s_age(a),s_name(n){} int get_age(){return s_age;} }; int main(){ father f; son s; cout<<f.get_age()<<endl; cout<<s.get_age()<<endl; system("pause"); }

输出为:函数

1spa

0指针

在基类中的虚函数,就是要提示用户在派生类中要从新定义。code

当基类中的虚函数定义时,是使用指针或者引用做为参数,那么在运行是,要判断传入的参数,是基类的对象,仍是派生类的对象。对象

若是是基类的对象,则调用基类中的虚函数定义。blog

若是是派生类的对象,则调用派生类中对基类虚函数的新定义的函数。get

相关文章
相关标签/搜索