下面是获取对象大小的不同方法。
- 成员函数存储在C ++中的哪里
- 介绍对象的大小。
- 没有结构填充的对象大小
- 具有结构填充的对象的大小
- 具有静态数据成员的对象的大小。
- 具有虚拟功能的对象的大小
- 具有继承的对象的大小
- C ++中空类的大小?
- 具有虚函数的空类的大小?
1.成员函数存储在C ++中的什么位置
成员功能代码将存储在程序的代码段中。因此,如何创建对象,成员函数只有1个副本,并且所有对象都将引用该代码段地址。
2.介绍对象的大小。
简单来说,对象的大小等于非静态数据成员和vptr的总大小。
在接下来的一系列示例中,我们将看到对象大小在不同条件下如何不同。
3.没有结构填充的对象大小
在下面的示例中,我们将看到没有结构填充的对象的大小。
/* * Author : [email protected] * Copyright: @ 前开发者教程.com */ #include <iostream> using namespace std; class Example { int i_num; char c_num; int i_num1; char c_num2; }; int main() { Example e; cout<<"The size is "<< sizeof(e)<<endl; }
输出:
The size is 16
由于存在结构填充,因此
int i_num; = 4 bytes char c_num; = 4 bytes int i_num1; = 4 bytes char c_num2; = 4 bytes
4.具有结构填充的对象的大小
/* * Author : [email protected] * Copyright: @ 前开发者教程.com */ #include <iostream> using namespace std; class Example { int i_num; int i_num1; char c_num2; char c_num; }; int main() { Example e; cout<<"The size is "<< sizeof(e)<<endl; }
输出:
The size is 12
由于没有结构填充,因此
int i_num; = 4 bytes char c_num; = 4 bytes int i_num1; = 2bytes char c_num2; = 2 bytes
5.具有静态数据成员的对象的大小。
/* * Author : [email protected] * Copyright: @ 前开发者教程.com */ #include <iostream> using namespace std; class Example { static int i_num; int i_num1; }; int main() { Example e; cout<<"The size is "<< sizeof(e)<<endl; }
输出:
The size is 4
由于静态数据成员将存储在共享存储中,因此对象中将仅存在非静态成员。
6.具有虚拟功能的物体的尺寸
/* * Author : [email protected] * Copyright: @ 前开发者教程.com */ #include <iostream> using namespace std; class Example { int i_num1; virtual void display() { cout<<"this is a function"; } }; int main() { Example e; cout<<"The size is "<< sizeof(e)<<endl; }
输出:
The size is 14
这里
int将占用4个字节。
_vptr将占用12个字节
7.带有继承的对象的大小
/* * Author : [email protected] * Copyright: @ 前开发者教程.com */ #include <iostream> using namespace std; class Base { public: int i_num1; }; class Derived: public Base { public: int i_num2; }; int main() { Derived d; cout<<"The size is "<< sizeof(d)<<endl; }
输出:
The size is 8
这里
4 bytes from base class int variable 4 bytes from derived class int variable
8. C ++中空类的大小?
/* * Author : [email protected] * Copyright: @ 前开发者教程.com */ #include <iostream> using namespace std; class Base { }; int main() { Base b; cout<<"The size is "<< sizeof(b)<<endl; }
输出:
The size is 1
为什么空对象的大小为1?
因为如果一个类有多个对象,则每个对象将具有唯一的内存位置。因此,如果一个类为空,那么该位置将存储什么?
因此,保留的最少内存为1。
9.具有虚函数的空类的大小?
/* * Author : [email protected] * Copyright: @ 前开发者教程.com */ #include <iostream> using namespace std; class Base { virtual void display() { } }; int main() { Base b; cout<<"The size is "<< sizeof(b)<<endl; }
输出:
The size is 8
由于_vptr需要8个字节,因此对象的大小为8个字节。
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |