变量与类型
auto 自动推导、const/constexpr、类型转换、初始化方式
变量与类型
C++ 兼容 C 的所有类型,同时引入了 auto、constexpr 和更丰富的初始化方式。
学完本章你将: 掌握 auto 自动推导、const/constexpr 区别、统一初始化 {}、类型转换。
C++ 初始化方式
cpp
#include <iostream>
int main() {
// C 风格(仍然可用)
int a = 10;
// C++ 统一初始化(推荐)
int b{10}; // 大括号初始化
int c = {10}; // 等价
// auto 自动推导
auto d = 42; // int
auto e = 3.14; // double
auto f = "hello"; // const char*
// 必须显式类型时
std::string s = "hello world";
std::vector<int> v = {1, 2, 3, 4, 5};
return 0;
}
auto —— 类型推导
cpp
auto i = 10; // int
auto d = 3.14; // double
auto s = std::string{"hello"}; // std::string
auto v = std::vector{1, 2, 3}; // std::vector<int>
// 用于复杂类型时特别方便
std::map<std::string, std::vector<int>> m;
auto it = m.begin(); // 不用写 std::map<...>::iterator
💡 auto 不是"动态类型"——类型在编译时就已确定,运行时不会变。
const vs constexpr
cpp
const int N = 100; // 只读(可能编译期也可能运行期)
constexpr int M = 100; // 编译期常量(保证编译期求值)
int arr1[N]; // 不总是合法(取决于编译器)
int arr2[M]; // 总是合法
// constexpr 函数:编译期计算
constexpr int square(int x) { return x * x; }
int arr3[square(10)]; // int arr3[100];