zoukankan      html  css  js  c++  java
  • 一些疑问

    看到书上的代码之后,产生了一些疑问,还请大佬指教一下
    程序如下:

    #include<iostream>
    using namespace std;
    class Base1{
    	public:
    		virtual void display()const;
    };
    void Base1::display()const{
    	cout<<"Base1::display()"<<endl;
    }
    class Base2:public Base1{
    	public:
    		void display()const;
    };
    void Base2::display()const{
    	cout<<"Base2::display()"<<endl;
    }
    class Derived:public Base2{
    	public:
    		void display()const;
    };
    void Derived::display()const{
    	cout<<"Derived::display()"<<endl;
    }
    void fun(Base1 *ptr){
    	ptr->display();
    }
    int main()
    {
    	Base1 base1;
    	Base2 base2;
    	Derived derived;
    	fun(&base1);
    	fun(&base2);
    	fun(&derived);
    	return 0;
    }
    

    这是书上讲虚函数的时候的那道例题
    ………………………………………………………………………………………………………………………………………………………………………………………………………………
    第一个疑问:
    我把虚函数去掉,想试用一下赋值兼容规则,程序变成了下面的样子

    #include<iostream>
    using namespace std;
    class Base1{
    	public:
    		 void display()const;
    };
    void Base1::display()const{
    	cout<<"Base1::display()"<<endl;
    }
    class Base2:public Base1{
    	public:
    		void display()const;
    };
    void Base2::display()const{
    	cout<<"Base2::display()"<<endl;
    }
    class Derived:public Base2{
    	public:
    		void display()const;
    };
    void Derived::display()const{
    	cout<<"Derived::display()"<<endl;
    }
    void fun(Base1 *ptr){
    	ptr->display();
    }
    int main()
    {
    	Base1 base1;
    	Base2 base2;
    	Derived derived;
    	fun(&base1);
    	fun(&base2);
    	fun(&derived);
    	return 0;
    }
    

    但是呐,运行结果不尽人意

    因为呐,书上将赋值兼容规则的时候是把display()声明为内联函数的,这里我就不是很明白为什么会这样了……还请大佬指导一下
    ……………………………………………………………………………………………………………………………………………………………………………………………………
    第二个问题
    我把第12行和14行的const去掉了

    #include<iostream>
    using namespace std;
    class Base1{
    	public:
    		virtual void display()const;
    };
    void Base1::display()const{
    	cout<<"Base1::display()"<<endl;
    }
    class Base2:public Base1{
    	public:
    		virtual void display ();
    };
    void Base2::display(){
    	cout<<"Base2::display()"<<endl;
    }
    class Derived:public Base2{
    	public:
    		void display()const ;
    };
    void Derived::display()const{
    	cout<<"Derived::display()"<<endl;
    }
    void fun(Base1 *ptr){
    	ptr->display();
    }
    int main()
    {
    	Base1 base1;
    	Base2 base2;
    	Derived derived;
    	fun(&base1);
    	fun(&base2);
    	fun(&derived);
    	return 0;
    }
    

    结果就变化了……这个也请大佬讲解一下

  • 相关阅读:
    JS获取今天的日期
    领域模型vs数据模型,应该怎么用?
    如何让技术想法更容易被理解?
    如何做好技术 Team Leader
    回归分析中常见的“门槛模型”!
    有了数据湖,距离数据仓库消失还有几年?
    数据治理 VS 公司治理、IT治理、数仓治理
    Sentence-seven basic patterns 英语句子结构
    VM的Linux CentOS系统的VMTools的手动安装
    linux下IPTABLES配置详解
  • 原文地址:https://www.cnblogs.com/Nicholastwo/p/9157748.html
Copyright © 2011-2022 走看看