数据类型
翻译整理自 cppreference - 类型 与 basic types。
1. 基本类型
| 类型 | 含义 |
|---|---|
bool |
布尔,true/false |
char / signed char / unsigned char |
1 字节 |
char8_t (C++20) |
UTF-8 字符 |
char16_t / char32_t (C++11) |
UTF-16 / UTF-32 |
wchar_t |
宽字符 |
short / unsigned short |
≥2 字节 |
int / unsigned |
通常 4 字节 |
long / unsigned long |
4 或 8 |
long long (C++11) |
≥8 字节 |
float / double / long double |
浮点 |
size_t |
由 <cstddef> 提供 |
定长类型用 <cstdint>:
#include <cstdint>
int32_t a;
uint64_t b;2. void
void f(void); // 等价 void f();
void* p; // 通用指针
3. enum 与 enum class
enum Color { Red, Green, Blue };
Color c = Red;
int i = c; // 可隐式转 int(C 风格 enum 弱点)
enum class Color2 { Red, Green, Blue }; // 强类型枚举(C++11)
Color2 c2 = Color2::Red;
// int j = c2; // ❌ 必须显式 static_cast
4. 字符串 std::string
#include <string>
std::string s = "Hello";
s += ", world";
s.length();
s.substr(0, 3); // "Hel"
s.find("world");
s[0] = 'h';
s.empty();
if (s == "hello") { ... }raw string(C++11)
std::string raw = R"(C:\new\folder)";
std::string multi = R"(
multi-line
)";string_view(C++17)
只读视图,无拷贝:
#include <string_view>
void f(std::string_view sv);
f("hello");
f(std::string("hello"));5. 数组与 std::array
int arr[5] = {1, 2, 3, 4, 5};
#include <array>
std::array<int, 5> a = {1, 2, 3, 4, 5}; // 固定大小容器
a.size();
a[0];
for (int x : a) std::cout << x;6. 动态数组 std::vector
#include <vector>
std::vector<int> v = {1, 2, 3};
v.push_back(4);
v.pop_back();
v.size();
v[0];
v.at(0); // 越界抛异常
v.resize(10);
v.clear();7. 类型转换
隐式
int i = 3;
double d = i; // 安全
int j = 3.7; // 截断,但有警告
显式
double pi = 3.14;
int n = static_cast<int>(pi);8. decltype 与 auto
int x = 0;
decltype(x) y = 1; // int
auto i = 0; // int
auto& r = x; // 引用
const auto& cr = x; // const 引用
9. 结构体 struct
struct Point {
int x, y;
};
Point p{1, 2};
Point q = {3, 4}; // 旧式
小结
C++ 数据类型在 C 基础上多了 bool、string、vector、enum class、定长整型等,写代码更安全方便。