zoukankan      html  css  js  c++  java
  • 一道关于C++ 继承/虚函数 笔试题

    #include "stdafx.h"
    #include "stdio.h"
    #include "string.h"
    
    
    class Father
    {
    public:
    	name()
    	{printf("father name\n");};
    	
    	virtual call()
    	{printf("father call\n");};
    	
    };
    
    
    
    class Son: public Father
    {
    public:
    	name()
    	{printf("Son name\n");};
    	
    	virtual call()
    	{printf("Son call\n");};
    	
    };
    
    main()
    {
    	
    	Son *Son1=new Son();
    	Father *father1=(Father *)Son1;
    	
    	father1->call();
    	father1->name();
    	
    	((Son *)(father1))->call();
    	((Son *)(father1))->name();
    
    
    	Father *f2=new Father();
    	Son *s2=(Son*)f2;
    	s2->call();
    	s2->name();
    	
    	((Father *)(s2))->call();
    	((Father *)(s2))->name();
    }
    output::
    Son call
    father name
    Son call
    Son name
    father call
    Son name
    father call
    father name
    

    虚函数的调用通过虚函数指针来调用,如果new的对象是Son的,则不管它转化成什么指针,它的指针都是Son内部的,与指针类型无关,只与指针地址有关

    非虚函数的调用则由指针类型决定

  • 相关阅读:
    Manager Test and DAO
    07-图
    06-排序
    05-查找
    第04次作业-树
    第03次作业-栈和队列
    week-02 线性表
    week01—绪论
    使用promise封装el-form多个表单校验
    $slot受slot-scope影响,导致$slot中的key消失
  • 原文地址:https://www.cnblogs.com/yangyh/p/2072393.html
Copyright © 2011-2022 走看看