-
-
[原创]用C语言模拟c++的对象生命周期过程
-
发表于:
2011-6-11 01:38
6564
-
个人感觉c和c++最大的不同就是c++的编译器更勤快,为我们作了更多的工作。比如计算偏移以及在对象生命周期结束时添加相应析构函数的调用。
如下面简单的c++代码
#include <stdio.h>
class CBase
{
public:
CBase():
m_nTest(0)
{
printf( "CBase constructor.\n" );
}
virtual ~CBase()
{
printf( "CBase destructor.\n" );
}
void Test()
{
printf( "CBase::Test m_nTest=%d\n", m_nTest );
}
virtual void VirtualTest()
{
printf( "CBase::VirtualTest\n" );
}
protected:
int m_nTest;
};
class CDerived : public CBase
{
public:
CDerived():
m_nTest(1)
{
printf( "CDirived constructor\n" );
}
virtual ~CDerived()
{
printf( "CDerived destructor\n" );
}
void Test()
{
printf( "CDerived::Test m_nTest=%d ; CBase::m_nTest=%d\n", m_nTest, CBase::m_nTest );
}
virtual void VirtualTest()
{
printf( "CDerived::VirtualTest\n" );
}
private:
int m_nTest;
};
int main()
{
CDerived derive;
CBase *pbase = &derive;
pbase->VirtualTest();
pbase->Test();
derive.Test();
return 0;
}
[注意]传递专业知识、拓宽行业人脉——看雪讲师团队等你加入!