• C++类继承示例


    C++的子类与孙子类都实现了虚函数时,孙子类的实现会覆盖掉子类的实现。

    继承的最主要的应用就是把不同的类放到一个数组中,然后遍历调用同名函数。

    实例如下:

    #include <iostream>
    #include <stdlib.h>
    #include <vector> 
    using namespace std;
    
    class Parent{
    	protected:
    		string pname;
    	public:
    		Parent(string name){
    			pname=name;	
    		}
    		
    		virtual void printName(){};
    };
    
    class Child: public Parent{
    	protected:
    		string cname;
    	public:
    		Child(string name):Parent(name){
    			cname=name;
    		}
    	
    		virtual void printName(){
    			cout<<"This is child, cname is "<<cname<<", pname is "<<pname<<endl;
    		}
    };
    
    class GrandChild: public Child{
    	private:
    		string gname;
    		
    	public:
    		GrandChild(string name):Child(name){
    			gname=name;
    		}
    		
    		virtual void printName(){
    			cout<<"This is grandchild, gname is "<<gname<<", cname is "<<cname<<", pname is "<<pname<<endl;
    		}
    };
    
    int main(){
    	string name="C";
    	Child child(name);
    	name="GC";
    	GrandChild gchild(name);
    	
    	vector<Parent*> mlist;
    	mlist.push_back(dynamic_cast<Parent*>(&child));
    	mlist.push_back(dynamic_cast<Parent*>(&gchild));
    	
    	for(int i=0;i<mlist.size();++i){
    		mlist[i]->printName();
    	}
    }
    

    注意子类与孙子类的printName函数前的virtual可加可不加,都可以正确运行……不知道哪个才是正确写法= =

     

  • 相关阅读:
    php的rabbitmq扩展(未测试)
    rabbitmq安装
    windows操作系统安装jdk以及配置环境变量
    chrome设置user-agent
    pycharm中快捷键ctrl+c,ctrl+v,ctrl+f失效问题解决
    chrome设置user agent
    Pycharm鼠标滚动控制字体大小
    mouse事件实现可拖拽的div
    DOM事件委托
    !heap 手动查询内存泄漏
  • 原文地址:https://www.cnblogs.com/plwang1990/p/4274189.html
Copyright © 2020-2023  润新知