加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 创业 > C语言 > 正文

[c++] sizeof 用法

发布时间:2020-12-15 00:03:59 所属栏目:C语言 来源:网络整理
导读:sizeof operator 获取对象或类型的大小,以byte为单位。只有对象的确切大小可以被知道时才能使用。 返回值类型为std::size_t 语法 sizeof( type ) (1) sizeof expression (2) 解释 (1)返回类型的对象表示的字节大小 (2)返回表达式返回类型的对象表示的字节大

sizeof operator

获取对象或类型的大小,以byte为单位。只有对象的确切大小可以被知道时才能使用。
返回值类型为std::size_t

语法

sizeof( type )    (1)    
sizeof expression    (2)    

解释

(1)返回类型的对象表示的字节大小

(2)返回表达式返回类型的对象表示的字节大小

注意事项

  1. 根据计算机的类型不同,一个byte的bit数可能不同,精确数字参照CHAT_BIT

  2. 当应用到类类型时,其结果是该类对象的大小,以及将该对象置于数组中所需的任何额外填充

  3. 当应用到一个空的类时,sizeof总是返回1

  4. 当sizeof运算符用于引用,结果和sizeof应用到对象本身一样

  5. sizeof的常见用法是sizeof array / sizeof array[0]

  6. 当应用到表达式时,表达式不会被计算

示例


struct Empty {};
struct Base { int a; };
struct Derived : Base { int b; };
struct Bit { unsigned bit: 1; };

int main(){
Empty e;
Derived d;
Base& b = d;
Bit bit;
int a[10];
std::cout << "size of empty class: " << sizeof e << 'n'
<< "size of pointer : " << sizeof &e << 'n'
// << "size of function: " << sizeof(void()) << 'n' // error
// << "size of incomplete type: " << sizeof(int[]) << 'n' // error
// << "size of bit field: " << sizeof bit.bit << 'n' // error
<< "size of array of 10 int: " << sizeof(int[10]) << 'n'
<< "size of array of 10 int (2): " << sizeof a << 'n'
<< "length of array of 10 int: " << ((sizeof a) / (sizeof *a)) << 'n'
<< "length of array of 10 int (2): " << ((sizeof a) / (sizeof a[0])) << 'n'
<< "size of the Derived: " << sizeof d << 'n'
<< "size of the Derived through Base: " << sizeof b << 'n';

}

程序的输出如下

size of empty class: 1
size of pointer : 8
size of array of 10 int: 40
size of array of 10 int (2): 40
length of array of 10 int: 10
length of array of 10 int (2): 10
size of the Derived: 8
size of the Derived through Base: 4

程序中带注释的三行是不能使用sizeof的情况,还有一些不能使用sizeof的情况如下:

  1. Functions. (However,sizeof can be applied to pointers to functions.)

  2. Bit fields.

  3. Undefined classes.

  4. The type void.

  5. Dynamically allocated arrays.

  6. External arrays.

  7. Incomplete types.

  8. Parenthesized names of incomplete types.

参考:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读