介绍
在本系列的教程中,我要讨论一些ATL的内部工作方式以及它所使用的技术。
在讨论的开始,让我们先看看一个程序的内存分布。首先,编写一个简单的程序,它没有任何的数据成员,你可以看看它的内存结构。
程序1.
#include <iostream> using namespace std;
class Class { };
int main() { Class objClass; cout << "Size of object is = " << sizeof(objClass) << endl; cout << "Address of object is = " << &objClass << endl; return 0; } |
这个程序的输出为:
Size of object is = 1 Address of object is = 0012FF7C |
现在,如果我们向类中添加一些数据成员,那么这个类的大小就会是各个成员的大小之和。对于模板,也依然是这样:
程序2.
#include <iostream> using namespace std;
template <typename T> class CPoint { public: T m_x; T m_y; };
int main() { CPoint<int> objPoint; cout << "Size of object is = " << sizeof(objPoint) << endl; cout << "Address of object is = " << &objPoint << endl; return 0; } |
现在程序的输出为:
Size of object is = 8 Address of object is = 0012FF78 |
那么,再向程序中添加继承。现在我们使Point3D类继承自Point类,然后来看看程序的内存结构:
程序3.
#include <iostream> using namespace std;
template <typename T> class CPoint { public: T m_x; T m_y; };
template <typename T> class CPoint3D : public CPoint<T> { public: T m_z; };
int main() { CPoint<int> objPoint; cout << "Size of object Point is = " << sizeof(objPoint) << endl; cout << "Address of object Point is = " << &objPoint << endl;
CPoint3D<int> objPoint3D; cout << "Size of object Point3D is = " << sizeof(objPoint3D) << endl; cout << "Address of object Point3D is = " << &objPoint3D << endl;
return 0; } |
程序的输出为:
Size of object Point is = 8 Address of object Point is = 0012FF78 Size of object Point3D is = 12 Address of object Point3D is = 0012FF6C |
这一程序演示了派生类的内存结构,它表明派生类的对象所占据的内存为它本身的数据成员和它基类的成员之和。
当虚函数加入到这个派对中的时候,一切就变得都有意思了。请看下面的程序:
程序4.
#include <iostream> using namespace std;
class Class { public: virtual void fun() { cout << "Class::fun" << endl; } };
int main() { Class objClass; cout << "Size of Class = " << sizeof(objClass) << endl; cout << "Address of Class = " << &objClass << endl; return 0; } |
程序的输出为:
Size of Class = 4 Address of Class = 0012FF7C |
并且,在我们添加了多于一个的虚函数之后,会变得更加有趣:
程序5.
#include <iostream> using namespace std;
class Class { public: virtual void fun1() { cout << "Class::fun1" << endl; } virtual void fun2() { cout << "Class::fun2" << endl; } virtual void fun3() { cout << "Class::fun3" << endl; } };
int main() { Class objClass; cout << "Size of Class = " << sizeof(objClass) << endl; cout << "Address of Class = " << &objClass << endl; return 0; } |
这个程序的输出和前一个程序一模一样,让我们再做一个实验来更好地弄懂这件事吧。
|