zoukankan      html  css  js  c++  java
  • 关于多态代码和运行结果

    #include <iostream>
    #pragma hdrstop
    using std::cout;
    using std::endl;
    //---------------------------------------------------------------------------
    #pragma argsused
    //---------------------------------------------------------------------------
    class Base {
    public:
    	Base() { };
    	virtual void DisplayMessage() {
    		cout << "Displaying Message from an object of Base class" << endl;
    	};
    };
    //---------------------------------------------------------------------------
    class DerivedFirst : public Base {
    public:
    	DerivedFirst() { };
    	void DisplayMessage() {
    		cout << "Displaying Message from an object of DerivedFirst class" << endl;
    	}
    };
    //---------------------------------------------------------------------------
    class DerivedSecond : public Base {
    public:
    	DerivedSecond() { };
    	void DisplayMessage() {
    		cout << "Displaying Message from an object of DerivedSecond class" << endl;
    	}
    };
    //---------------------------------------------------------------------------
    class DerivedThird : public Base {
    public:
    	DerivedThird() { };
    };
    //---------------------------------------------------------------------------
    int main()
    {
    	// create a base class object
    	Base* bc = new Base();
    	bc->DisplayMessage();
    	// delete the base class object and assign it to DerivedFirst object
    	delete bc;
    	bc = new DerivedFirst();
    	bc->DisplayMessage();
    	// delete the base class object and assign it to DerivedSecond object
    	delete bc;
    	bc = new DerivedSecond();
    	bc->DisplayMessage();
    	// delete the base class object and assign it to DerivedThird object
    	delete bc;
    	bc = new DerivedThird();
    	bc->DisplayMessage();
    	delete bc;
    	return EXIT_SUCCESS;
    }
    //---------------------------------------------------------------------------
    

    函数主要作用:用基类声明的指针(Base* bc),指向派生类,如果派生类中有与基类中相同的方面就调用子类的方法,如果子类没有该方面,就调用基类自身的方法。
    基类中如果不加virtual 关键字,用用基类声明的指针,调用函数时只能调用基类自身的函数。

  • 相关阅读:
    文件编码转换
    mysql密码的奇怪问题
    python文件读写
    python中JSON的使用
    mysql默认字符编码的修改
    烧写uboot与linux操作系统,安装Samba,jlink驱动安装
    Busybox是什么?
    ubuntu 搭建GTK+以及glade2集成开发环境的一些方法
    Ubuntu linux安装ssh server
    UBoot启动过程(国嵌)
  • 原文地址:https://www.cnblogs.com/zhangdongsheng/p/2010237.html
Copyright © 2011-2022 走看看