sizeof操作符

本文详细介绍了C++中sizeof操作符的功能与用法,通过多个示例解释了如何获取不同数据类型及对象的字节长度,并对比了在指针、引用和基本类型上的表现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

sizeof操作符的作用:返回一个对象或类型名的字节长度

一、sizeof(type name)

二、sizeof(object)

三、sizeof object



#include <iostream>
#include <cassert>
#include <vector>
#include <cstddef>
#include <string>
using namespace std;


int main()
{

	/*应用在指针类型上的sizeof操作符返回的是包含该类型地址所需的内存长度。
	应用在引用类型上的sizeof操作符返回的是包含被引用对象所需的内存长度。*/
	size_t ia;
	ia =sizeof(ia);
	ia=sizeof ia;

	ia=sizeof(int);
	int *pi =new int[12];
	cout<<"pi: "<<sizeof(pi)<<endl<<"*pi "<<sizeof(*pi)<<endl;

	cout<<"---------------->\t"<<endl;
	
	string str=("test");
	cout<<"str : "<<sizeof(str)<<endl;
	string str1=(" black ");
	string str2=("With you l ride or die tonight !");
	string *ps =&str1;
	cout<<"str1: "<<sizeof(str1)<<endl
		<<"str2: "<<sizeof(str2)<<endl
		<<"ps: "<<sizeof(ps)<<endl
		<<"*ps: "<<sizeof(*ps)
		<<endl;


	//当sizeof应用在char类型上,在所有的实现里返回的都是1
	cout<<"short: \t"<<sizeof(short)<<endl;
	cout<<"short: \t"<<sizeof(short*)<<endl;
	cout<<"short& : "<<sizeof(short&)<<endl;
	cout<<"short[3]: "<<sizeof(short[3])<<endl;

	size_t char_size=sizeof(char);
	cout<<char_size<<endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值