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内部的,与指针类型无关,只与指针地址有关

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

    from:http://www.cnblogs.com/yangyh/archive/2011/06/04/2072393.html

  • 相关阅读:
    组合数问题
    [Repost] 悬线法
    图论 List
    杂项 List
    动态规划 List
    Binary Search
    树状数组,Fenwick Tree
    HDU1086判断线段相交
    高效大数模板
    HDUOJ2298三分加二分
  • 原文地址:https://www.cnblogs.com/lidabo/p/2726928.html
Copyright © 2011-2022 走看看