博客
关于我
c++基础——类的大小
阅读量:490 次
发布时间:2019-03-06

本文共 927 字,大约阅读时间需要 3 分钟。

说明

关于c++中类的大小的问题,首先看下面的一个例子:

#include 
using std::cout;using std::endl;class Father {private: int age;public: void showAge() { cout << "Age: " << age << endl; }};class Mother {};class Son : public Father {};class Sister : public Father {private: static int a;};int main() { cout << "Size of int : " << sizeof(int) << endl; cout << "Size of Father: " << sizeof(Father) << endl; cout << "Size of Mother: " << sizeof(Mother) << endl; cout << "Size of Son : " << sizeof(Son) << endl; cout << "Size of Sister: " << sizeof(Sister) << endl; return 0;}

下面是执行的结果:

从上面的结果可以看出以下的几点:

1. 类中的方法并不是算在类的大小中。(见int的大小和Father的大小)

2. 空的类的大小是1个字节,而不是0。(见Mother的大小)

3. 虽然子类不能访问父类的private变量,但是在子类中也包含这个变量。(见Father和Son的大小)

4. static变量的大小不包含在类中。(见Father和Sister的大小)

以上是在没有虚函数的情况下,如果将Father中的showAge()修改成虚函数:

class Father {private:	int age;public:	virtual void showAge() {		cout << "Age: " << age << endl;	}};

结果如下:

多出来的4个字节实际上是指向虚函数表的指针大小。

 

你可能感兴趣的文章
node模块化
查看>>
node模块的本质
查看>>
node环境下使用import引入外部文件出错
查看>>
node环境:Error listen EADDRINUSE :::3000
查看>>
Node的Web应用框架Express的简介与搭建HelloWorld
查看>>
Node第一天
查看>>