gpt4 book ai didi

c++ - 对象表示和运算符sizeof的定义

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:52:22 26 4
gpt4 key购买 nike

3.9/4给出了对象表示概念的定义:

[基本类型]

The object representation of an object of type T is the sequence of N unsigned char objects taken up by the object of type T, where N equals sizeof(T).

但是sizeof操作符的定义如下:

[表达式大小]

The sizeof operator yields the number of bytes in the object representation of its operand.

特别是:

When applied to a class, the result is the number of bytes in an object of that class including any padding required for placing objects of that type in an array

我想通过示例考虑该定义:

struct A {
int a; //sizeof(a) is implementation defined
long b; //sizeof(b) is implementation defined
char c; //sizeof(c) is 1 by definition
// Padding, problbly equals to 3 butes
}

sizeof(A) 是如何通过实现计算的?我们只计算 sizeof(a) + sizeof(b) + sizeof(c) + padding 的总和。

但是将那种类型的对象放入数组中所需的条件是关于什么的?

最佳答案

您可以简单地计算结构的大小:

long size = sizeof(struct A);  

如果你想要一个struct A的数组,

struct A arr[/* Size of array */];

关于c++ - 对象表示和运算符sizeof的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26228577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com