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

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

  • 相关阅读:
    window.setInterval
    用gcc/g++编译winsock程序
    Yii 三表关联 角色表、角色权限连接表、权限表
    访问CGI程序时不添加 /cgi-bin/ 目录也可访问
    Linux 目录递归赋权,解决 Linux权限不够
    Linux 下用C语言连接 sqlite
    ORACLE中添加删除主键
    Linux 杀死进程
    Oracle 查询重复数据
    exlipse php 插件安装地址
  • 原文地址:https://www.cnblogs.com/Nicholastwo/p/9157748.html
Copyright © 2011-2022 走看看