虚函数

时间:2022-04-22
本文章向大家介绍虚函数,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

虚函数

代码如下定义:

// 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");
}

输出为:

1

0

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

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

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

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