类型、变量与推导

C++ 是一门强类型语言——每一个变量都有明确的类型,且类型在编译期确定。理解类型系统是写出安全、高效代码的基础。本章将从基本类型出发,逐步介绍现代 C++ 的初始化方式、auto 推导机制以及编译期常量。

基本类型 (Fundamental Types)

C++ 提供了一组内建的基本类型,用于表示整数、浮点数、布尔值和字符。

整数类型

整数类型按照宽度从小到大依次为:

类型 典型大小 范围(有符号) 用途
std::int8_t 1 字节 -128 ~ 127 精确 8 位
short 2 字节 -32768 ~ 32767 较少使用
int 4 字节 约 ±21 亿 默认整数选择
std::int32_t 4 字节 约 ±21 亿 需要精确 32 位
long long 8 字节 约 ±9.2 × 1018 大整数
std::int64_t 8 字节 约 ±9.2 × 1018 需要精确 64 位
std::size_t 4/8 字节 0 ~ 最大地址 表示大小和索引

如何选择整数类型?

  • 一般计算:用 int
  • 需要精确宽度(网络协议、文件格式):用 <cstdint> 中的 std::int32_t 等
  • 表示容器大小和索引:用 std::size_t(或配合 std::ssize_t)
  • 需要大整数:用 long long 或 std::int64_t

浮点类型

类型 大小 精度 用途
float 4 字节 约 7 位有效数字 图形、GPU 计算
double 8 字节 约 15 位有效数字 默认浮点选择

其他基本类型

bool is_valid{true};     // 布尔值:true 或 false
char letter{'A'};        // 单个字符(1 字节)
char8_t utf8_char{u8'x'}; // UTF-8 字符(C++20)

使用固定宽度类型需要包含头文件

std::int32_t、std::size_t 等类型定义在 <cstdint> 和 <cstddef> 中。

变量声明与初始化

C++ 有多种变量初始化方式。现代 C++ 推荐使用花括号初始化(brace initialization),也称为统一初始化。

三种初始化语法

int a = 42;    // 拷贝初始化(C 风格)
int b(42);     // 直接初始化(构造函数风格)
int c{42};     // 花括号初始化(现代 C++ 推荐)✓

对于简单的内建类型,三者的效果相同。但花括号初始化有一个关键优势:防止窄化转换。

窄化转换保护

double pi{3.14159};

// 花括号初始化会在编译期报错,防止数据丢失
int x{pi};     // [错误] 编译错误!double → int 是窄化转换

// 而传统方式只会静默截断
int y = pi;    // [注意] 编译通过,y == 3,小数部分丢失
int z(pi);     // [注意] 同上,静默截断

窄化转换是 bug 的常见来源

当一个 double 被赋值给 int,或一个大整数被赋值给小整数时,数据会被静默截断。花括号初始化通过编译期检查帮你发现这类问题。

花括号初始化适用于所有场景

#include <string>
#include <vector>

// 变量定义
int count{0};
double temperature{36.5};
std::string greeting{"Hello, C++!"};

// 容器初始化
std::vector<int> numbers{1, 2, 3, 4, 5};

// 结构体成员
struct Point {
    double x{0.0};
    double y{0.0};
};

// 函数返回值
Point make_origin() {
    return {0.0, 0.0};  // 花括号直接构造返回值
}

auto 类型推导

auto 关键字让编译器根据初始化表达式自动推导变量类型。它不会损失任何类型安全性——类型仍然在编译期确定,只是你不需要手动写出来。

基本用法

auto x = 42;                    // int
auto pi = 3.14;                 // double
auto name = std::string{"C++"}; // std::string
auto flag = true;               // bool
auto letter = 'A';              // char

auto 需要初始化器

auto x; 是不合法的——编译器必须从初始化表达式推导类型。这反而是好事:它迫使你在声明变量时就给出初始值,避免了未初始化变量的 bug。

auto 与 const / 引用

const auto max_count = 100;      // const int
const auto& ref = name;          // const std::string&

auto& mutable_ref = name;        // std::string&(引用需要显式写出)

// auto 会丢弃顶层 const 和引用
const int ci = 42;
auto a = ci;        // int(不是 const int)
auto& b = ci;       // const int&(引用保留 const)

"几乎总是 auto" 风格 (Almost Always Auto)

许多现代 C++ 专家推荐尽可能使用 auto,理由是:

  • 避免冗余——右侧已经表明了类型,左侧不必重复
  • 防止意外转换——类型精确匹配初始化表达式
  • 更容易重构——修改函数返回类型时,调用方自动适配
  • 强制初始化——没有初始化器就无法用 auto
// 传统风格——类型写了两遍
std::vector<std::string> words = std::vector<std::string>{};
std::map<std::string, int>::iterator it = scores.begin();

// auto 风格——简洁清晰
auto words = std::vector<std::string>{};
auto it = scores.begin();

何时不用 auto?

当类型不能从右侧表达式一眼看出时,显式类型可能更清晰:

// 不够清晰——read_config() 返回什么?
auto config = read_config();

// 更清晰——明确表达意图
Config config = read_config();

根据团队约定灵活选择即可。

const 与 constexpr

C++ 提供两种"常量"机制:const 表示运行时不可变,constexpr 表示编译期可求值。

const —— 运行时常量

const int max_retries = 3;       // 值不可修改
const double tax_rate = 0.08;    // 运行时确定也可以

// const 变量的值可以在运行时确定
int user_input{};
std::cin >> user_input;
const int user_choice = user_input;  // OK:运行时确定,之后不可改

const 的含义是"一旦初始化就不能修改"。它的值可以在运行时才确定。

constexpr —— 编译期常量

constexpr int max_buffer = 1024;       // 编译期确定
constexpr double gravity = 9.8;        // 编译期确定
constexpr int square(int n) { return n * n; }
constexpr int area = square(5);        // 编译期计算 = 25

// constexpr 变量的值必须在编译期可知
int runtime_val = get_input();
constexpr int x = runtime_val;  // [错误] 编译错误!运行时值不能用于 constexpr

const vs constexpr:如何选择?

场景选择理由
数学常数(pi、e)constexpr编译期已知
配置上限(缓冲区大小)constexpr编译期已知
函数参数标记为不可修改const运行时传入
从用户输入获得的值const运行时才知道

原则:能用 constexpr 就用 constexpr。它给编译器更多优化机会,也能用于模板参数和数组大小。

constexpr 的实际优势

// constexpr 可以用于数组大小
constexpr int buffer_size = 256;
char buffer[buffer_size];  // OK

// constexpr 可以用于 static_assert
constexpr int version = 20;
static_assert(version >= 17, "Requires C++17 or later");

// constexpr 可以用于模板参数
std::array<int, buffer_size> data;  // OK

类型别名 (Type Aliases)

类型别名为已有类型创建一个新名字,提高代码可读性。现代 C++ 推荐使用 using 而非旧式的 typedef。

using 声明

// 现代风格:using(推荐)
using Velocity = double;
using Distance = double;
using StudentId = std::int32_t;
using Callback = std::function<void(int)>;
using StringVec = std::vector<std::string>;

// 使用别名定义变量
Velocity speed{120.5};
Distance traveled{1500.0};
StudentId id{2024001};

对比旧式 typedef

// 旧式:typedef(不推荐,但你会在旧代码中遇到)
typedef double Velocity;
typedef std::vector<std::string> StringVec;
typedef void (*FuncPtr)(int);  // 函数指针——难以阅读

// 现代 using 等价写法——清晰得多
using FuncPtr = void(*)(int);

为什么用 using 而非 typedef?

  • using 语法更直观:新名字在左,原类型在右
  • using 支持模板别名(typedef 不支持)
  • 函数指针等复杂类型用 using 可读性明显更好

统一初始化的好处

花括号初始化(也叫统一初始化)是现代 C++ 的核心改进之一。让我们总结它的关键优势。

优势一:防止窄化转换

int a{3.14};           // [错误] 编译错误:double → int 窄化
int b{1000000000000L}; // [错误] 编译错误:值超出 int 范围
char c{300};           // [错误] 编译错误:300 超出 char 范围

// 传统方式不会报错,静默丢失数据
int a = 3.14;          // [注意] a == 3,无任何警告
char c = 300;          // [注意] 未定义行为

优势二:语法统一

// 花括号在所有场景下通用
int x{10};                              // 基本类型
std::string s{"hello"};                 // 类类型
std::vector<int> v{1, 2, 3};           // 容器
Point p{3.0, 4.0};                      // 聚合类型
auto ptr = std::make_unique<int>(42);  // 智能指针(工厂函数)

优势三:避免 "Most Vexing Parse"

// 传统语法的陷阱:这是变量定义还是函数声明?
std::vector<int> data(std::istream_iterator<int>(std::cin),
                       std::istream_iterator<int>());
// 编译器将其解析为函数声明!

// 花括号消除歧义
std::vector<int> data{std::istream_iterator<int>{std::cin},
                       std::istream_iterator<int>{}};
// 明确是变量定义

注意:花括号与 std::initializer_list

当类同时提供 std::initializer_list 构造函数和普通构造函数时,花括号会优先匹配前者:

std::vector<int> v1(5, 0);  // 5 个元素,每个为 0
std::vector<int> v2{5, 0};  // 2 个元素:5 和 0

// 这是花括号初始化唯一需要注意的地方

完整示例

将本章内容综合运用:

#include <cstdint>
#include <iostream>
#include <string>
#include <vector>

// 类型别名——提高语义清晰度
using Celsius = double;
using Meters = double;
using StudentId = std::int32_t;

// 编译期常量
constexpr Meters earth_radius = 6'371'000.0;  // 数字分隔符 (C++14)
constexpr double pi = 3.14159265358979;
constexpr Celsius absolute_zero = -273.15;

int main() {
    // 花括号初始化
    int count{0};
    bool is_running{true};
    char grade{'A'};

    // auto 类型推导
    auto name = std::string{"Modern C++"};
    auto scores = std::vector<int>{95, 87, 92, 78, 100};
    auto earth_circumference = 2.0 * pi * earth_radius;

    // const:运行时常量
    const auto num_scores = scores.size();  // std::size_t

    // 输出
    std::cout << name << " course\n";
    std::cout << "Earth circumference: " << earth_circumference << " m\n";
    std::cout << "Number of scores: " << num_scores << "\n";
    std::cout << "Absolute zero: " << absolute_zero << " °C\n";

    return 0;
}

本章小结

  • C++ 基本类型包括整数(int、long long、std::int32_t)、浮点(double)、布尔和字符类型
  • 优先使用花括号初始化 {}——它能防止窄化转换,是最安全的初始化方式
  • 使用 auto 让编译器推导类型——减少冗余、强制初始化、便于重构
  • const 用于运行时不可变值,constexpr 用于编译期常量——优先选 constexpr
  • 使用 using 创建类型别名,替代旧式 typedef
  • 需要精确宽度整数时,使用 <cstdint> 中的固定宽度类型