ATL布幔之下的秘密
2006-07-22 22:55:08 来源:WEB开发网介绍
在本系列的教程中,我要讨论一些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
那么,再向程序中添加继承。现在我们使Point3D类继承自Point类,然后来看看程序的内存结构:
Address of object is = 0012FF78
程序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
更多精彩
赞助商链接