zoukankan      html  css  js  c++  java
  • 基类与派生类的对象调用

    下列代码之后的结果为(

    adcee

    #include<iostream>
    using namespace std;
    struct Base{
    	int i;
    	virtual int f() {
    		cout<<"a";
    		return 1;
    	}
    	virtual const Base &f() const {
    		cout<<"b";
    		return *this;
    	}
    	int g() {
    		cout<<"c";
    		return 3;
    	}
    };
    struct Derive:Base {
    	int i;
    	int f() {
    		cout<<"d";
    		return 4;
    	}
    	const Base &f() const{
    		cout<<"e";
    		return *this;
    	}
    	int f(int=0) {
    		cout<<"f";
    		return 6;
    	}
    	virtual int g() {
    		cout<<"g";
    		return 7;
    	}
    };
    
    int main() {
    	Derive d;
    	const Derive  d_const;
    	Base b,*p=&d;
    	const Base *p_const = &d_const;
    	b.f();
    	p->f();
    	p->g();
    	p_const->f();
    	d_const.f();
    }
    

      

    1.b.f(); 基类对象直接调用基类的f()函数,输出a
    2.p->f(); 派生类对象赋给基类的指针,由于f()在基类中是虚函数,根据基类指针指向的对象进行调用,因此调用派生类的int f()输出d
    3.p->g();基类中g()不是虚函数,调用基类的g()
    4.p_const->f();常对象,又由于基类中声明为虚,同理用派生类中的函数
    5.同理
     
     
    只有在通过基类指针(或引用)间接指向派生类子类型时多态性才会起作用。派生类的指针只调用自己的函数!基类指针的函数调用如果有virtual则根据多态性调用派生类的函数,如果没有virtual则是正常调用基类的函数。
    拥抱明天! 不给自己做枷锁去限制自己。 别让时代的悲哀,成为你人生的悲哀。
  • 相关阅读:
    BZOJ1208
    BZOJ1024
    BZOJ_day4&&DSFZ_day1
    BZOJ day2_plus
    BZOJ day2
    系统设计2:数据库设计
    设计模式8:外观模式
    系统设计1:概述
    设计模式7:模板方法模式
    九章算法班ladder题目梳理
  • 原文地址:https://www.cnblogs.com/dd2hm/p/7290366.html
Copyright © 2011-2022 走看看