一道关于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

原文地址:https://www.cnblogs.com/lidabo/p/2726928.html