zoukankan      html  css  js  c++  java
  • 【C++札记】赋值兼容

    赋值兼容的规则时在需要使用基类对象的任何地方都可以使用公有派生类对象来替代。公有继承派生类可获得基类中除构造函数,析构函数外的所有成员,能用基类解决的问题,派生类也能解决。更直白点说,如果一个类是从一个基类公有继承过来,那么这个派生类就可以替代基类,反过来基类不能替代派生类。

    常用赋值兼容情况:

    1.派生类对象赋值给基类对象。

    2.派生类对象初始化基类对象引用。

    3.派生类对象地址赋值给指向基类对象指针。

    #include <iostream>
    
    using namespace std;
    
    class Father
    {
    public:
    	void show()
    	{
    		cout << "Father	show()" << endl;
    	}
    
    	void showFather()
    	{
    		cout << "showFather()" << endl;
    	}
    };
    
    class Son : public Father
    {
    public:
    	void show()
    	{
    		cout << "Son	show()" << endl;
    	}
    
    	void showSon()
    	{
    		cout << "showSon()" << endl;
    	}
    };
    
    int main()
    {
    	Father father1;
    	Son son1;
    	father1 = son1;			//子类对象赋值给父类对象
    	father1.show();			//调用父类中的show()方法
    	father1.showFather();	//调用父类中的showFather()方法
    
    	Son son2;
    	Father& father2 = son2;	//子类对象初始化父类对象引用
    	father2.show();			//调用父类中的show()方法
    	father2.showFather();	//调用父类中的showFather()方法
    
    	Son son3;
    	Father* father3 = &son3;//子类对象地址赋值给指向父对象指针
    	father3->show();		//调用父类中的show()方法
    	father3->showFather();	//调用父类中的showFather()方法
    
    	getchar();
    }

     

  • 相关阅读:
    AGC037F Counting of Subarrays
    AGC025F Addition and Andition
    CF506C Mr. Kitayuta vs. Bamboos
    AGC032D Rotation Sort
    ARC101F Robots and Exits
    AGC032E Modulo Pairing
    CF559E Gerald and Path
    CF685C Optimal Point
    聊聊Mysql索引和redis跳表
    什么是线程安全
  • 原文地址:https://www.cnblogs.com/woniu201/p/11694511.html
Copyright © 2011-2022 走看看