标签:
转自:http://www.cnblogs.com/yangyh/archive/2011/06/04/2072393.html
首先这位作者, 因为看了这篇简短的一个博文, 我相同了关于虚函数方面的知识。
#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内部的,与指针类型无关,只与指针地址有关
非虚函数的调用则由指针类型决定
标签:
原文地址:http://www.cnblogs.com/jluzhsai/p/4374363.html