zoukankan      html  css  js  c++  java
  • 虚函数

    虚函数

    代码如下定义:

    // 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

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

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

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

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

  • 相关阅读:
    线程同步锁的使用方式
    EventBus简单封装
    Dagger2不自动生成daggerXXXcomponent
    android mvp模式
    第八天
    单词统计续
    学习进度第十一周
    第七天
    第六天
    第五天
  • 原文地址:https://www.cnblogs.com/xing901022/p/3422252.html
Copyright © 2011-2022 走看看