C++数据类型的基础分类

C++数据类型分为基本类型、派生类型和用户自定义类型。基本类型包括整型、浮点型、字符型和布尔型;派生类型涵盖数组、指针、引用等;用户自定义类型主要有结构体、联合体和类。

整型数据的关键细节

整型包括shortintlonglong long,长度因平台而异。标准规定:

  • short至少16位
  • int至少与short相同
  • long至少32位
  • long long至少64位

符号修饰符:

signed int a;   // 有符号(默认)
unsigned int b; // 无符号

浮点型精度与范围

  • float:32位,约7位有效数字
  • double:64位,约15位有效数字
  • long double:通常80位或更多

科学计数法示例:

double d = 3.14e5; // 314000

字符型与布尔型特性

  • char:至少8位,实际大小由编译器决定
  • wchar_t:宽字符,用于Unicode
  • bool:仅true/false,实际存储为1字节

转义字符:

'\n' // 换行
'\t' // 制表符
'\0' // 空字符

类型转换规则

隐式转换顺序: boolcharshortintlongfloatdoublelong double

显式转换方式:

int i = static_cast<int>(3.14); // C++风格
int j = (int)3.14;              // C风格

类型修饰符的应用

  • const:定义不可变量
  • volatile:防止编译器优化
  • mutable:允许const成员修改

组合示例:

const volatile int status_reg;

sizeof运算符的使用

获取类型/对象内存大小:

sizeof(int);       // 返回字节数
sizeof(var_name);  // 返回变量大小

自动类型推导

C++11引入的auto关键字:

auto x = 42;       // int
auto y = 3.14;     // double
auto z = "hello";  // const char*

类型别名定义

传统方式:

typedef int counter;

C++11新语法:

using counter = int;

字面量后缀说明

指定字面量类型:

auto a = 42u;    // unsigned
auto b = 3.14f;  // float
auto c = 42LL;   // long long

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐