-
-
[原创]用C语言模拟c++的对象生命周期过程
-
发表于:
2011-6-11 01:38
6565
-
个人感觉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;
}
[招生]科锐逆向工程师培训(2024年11月15日实地,远程教学同时开班, 第51期)