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;
    }
    

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

  • 相关阅读:
    八. 输入输出(IO)操作2.面向字符的输入流
    八. 输入输出(IO)操作1.输入输出基本概念
    七. 多线程编程11.线程的挂起、恢复和终止
    七. 多线程编程10.线程死锁
    nginx 配置身份验证 http_auth_basic_module
    liunx mysql 备份
    8080 端口只允许内网访问配置
    nginx 配置白名单
    liunx tomcat 运行模式apr
    liunx contos 7.4 安装redis集群
  • 原文地址:https://www.cnblogs.com/Nicholastwo/p/9157748.html
Copyright © 2011-2022 走看看