博客
关于我
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个字节实际上是指向虚函数表的指针大小。

 

你可能感兴趣的文章
Nginx + uWSGI + Flask + Vhost
查看>>
Nginx - Header详解
查看>>
Nginx - 反向代理、负载均衡、动静分离、底层原理(案例实战分析)
查看>>
nginx 1.24.0 安装nginx最新稳定版
查看>>
nginx 301 永久重定向
查看>>
nginx css,js合并插件,淘宝nginx合并js,css插件
查看>>
Nginx gateway集群和动态网关
查看>>
Nginx Location配置总结
查看>>
Nginx log文件写入失败?log文件权限设置问题
查看>>
Nginx Lua install
查看>>
nginx net::ERR_ABORTED 403 (Forbidden)
查看>>
Nginx SSL私有证书自签,且反代80端口
查看>>
Nginx upstream性能优化
查看>>
Nginx 中解决跨域问题
查看>>
nginx 代理解决跨域
查看>>
Nginx 动静分离与负载均衡的实现
查看>>
Nginx 反向代理 MinIO 及 ruoyi-vue-pro 配置 MinIO 详解
查看>>
nginx 反向代理 转发请求时,有时好有时没反应,产生原因及解决
查看>>
Nginx 反向代理解决跨域问题
查看>>
Nginx 反向代理配置去除前缀
查看>>