c++ Prime读书笔记7(sizeof)

来源:互联网 发布:java选择题 编辑:程序博客网 时间:2024/06/05 21:01

 siseof 操作符的作用是返回一个对象或类型名的字节长度它有以下三种形式

sizeof (type name );

sizeof ( object );

sizeof object;

 

// sizeof.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include <string>
#include <iostream>
#include <cstddef>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
 size_t ia;
 ia = sizeof( ia ); // ok
 ia = sizeof ia; // ok
 // ia = sizeof int; // 错误
 ia = sizeof( int ); // ok
 int *pi = new int[ 12 ];
 cout << "pi: " << sizeof( pi )//pi为指针,指针占用空间均为4
 << " *pi: " << sizeof( *pi )//*pi为数组第一个元素,其类型为int,占用空间为4
 << endl;
 // 一个string 的大小与它所指的字符串的长度无关
 string st1( "foobar" );
 string st2( "a mighty oak" );
 string *ps = &st1;
 string &ss = st1;
 cout << "string: "<< sizeof(string) 
 << " st1: " << sizeof( st1 )
 << " st2: " << sizeof( st2 )
 << " ps: " << sizeof( ps )
 << " *ps: " << sizeof( *ps )
 << " &ss: "<< sizeof( ss )
 << endl;
 cout << "short :/t" << sizeof(short) << endl;
 cout << "short* :/t" << sizeof(short*) << endl;
 cout << "short& :/t" << sizeof(short&) << endl;
 cout << "short[3] :/t" << sizeof(short[3]) << endl;
 return 0;
}
/*
pi: 4 *pi: 4
string: 32 st1: 32 st2: 32 ps: 4 *ps: 32 &ss: 32
short : 2
short* :        4
short& :        2
short[3] :      6
请按任意键继续. . .
正如上面的例子程序所显示的那样应用在指针类型上的sizeof 操作符返回的是包含该
类型地址所需的内存长度但是应用在引用类型上的sizeof 操作符返回的是包含被引用对
象所需的内存长度

*/

sizeof 操作符在编译时刻计算因此被看作是常量表达式它可以用在任何需要常量表
达式的地方如数组的维数或模板的非类型参数例如
// ok: 编译时刻常量表达式
int array[ sizeof( some_type_T )];