SyntaxHighlighter

2010年10月29日星期五

基类与派生类互转时需要注意void*类型


// Test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

class A
{
public:
A():a(0){}
int a;
void FnA(){printf("A %dn",a);}
virtual void VFnA(){printf("VA %dn",a);}
};


class B
{
public:
B():b(1){}
int b;
void FnB(){printf("B %dn",b);}
void FnB2(){printf("B2 %dn",b);}
virtual void VFnB(){printf("VB %dn",b);}
};

class C
{
public:
C():c(2){}
int c;
void FnC(){printf("C %dn",c);}
void FnC2(){printf("C2 %dn",c);}
void FnC3(){printf("C3 %dn",c);}
virtual void VFnC(){printf("VC %dn",c);}
};

class T : public A, public B, public C
{
public:
void FnT(){}
virtual void VFnA(){printf("TVA %dn",a);}
virtual void VFnB(){printf("TVB %dn",b);}
virtual void VFnC(){printf("TVC %dn",c);}
};

void Fn(C* c)
{
c->FnC();
}

void Fn2(void* p)
{
C* pC = (C*)p;
pC->FnC3();
}

void Fn3(void* p)
{
C* pC = (C*)p;
printf("Fn3:c=%d ",pC->c);
pC->VFnC();
}

int _tmain(int argc, _TCHAR* argv[])
{
T t;
A* pA = &t;
B* pB = &t;
C* pC = &t;

Fn(&t);
Fn2(&t);
Fn2((B*)&t);
Fn3(&t);
Fn3((B*)&t);
return 0;
}

//结果
//C 2
//C3 0
//C3 1
//Fn3:c=0 TVA 0
//Fn3:c=1 TVB 1

T的内存排布示意:
vfptr

没有评论:

发表评论