C++ 数据类型
基本数据类型
整型
int:通常为 4 字节,存储整数。short:2 字节,范围较小。long:4 或 8 字节,取决于系统。long long:8 字节,存储更大整数。
浮点型
float:4 字节,单精度浮点数。double:8 字节,双精度浮点数。long double:扩展精度浮点数。
字符型
char:1 字节,存储单个字符。wchar_t:宽字符,用于 Unicode。
布尔型
bool:存储true或false。
派生数据类型
数组
- 固定大小的同类型元素集合。
- 示例:
int arr[5] = {1, 2, 3, 4, 5};
指针
- 存储内存地址。
- 示例:
int* ptr = &var;
引用
- 变量的别名。
- 示例:
int& ref = var;
结构体与类
struct:组合不同类型的数据。class:支持数据封装与继承。
常用头文件及用途
输入输出
<iostream>:提供cin、cout等标准输入输出功能。#include <iostream> using namespace std; int main() { cout << "Hello, World!"; return 0; }
数学运算
<cmath>:包含数学函数如sqrt()、sin()。#include <cmath> double result = sqrt(25.0);
字符串处理
<string>:支持std::string类型及操作。#include <string> string str = "C++";
动态内存管理
<new>:提供动态内存分配功能。int* arr = new int[10]; delete[] arr;
算法与容器
<algorithm>:包含排序、查找等算法。<vector>:实现动态数组。#include <vector> vector<int> vec = {1, 2, 3};<bits/stdc++.h> 万能头
基础语法
变量声明与初始化
int a = 10; // 直接初始化 double b{3.14}; // 列表初始化控制结构
条件语句
if (a > b) { cout << "a is greater"; } else { cout << "b is greater"; }循环
for (int i = 0; i < 5; i++) { cout << i << endl; } while (a < 10) { a++; }
函数定义
int add(int x, int y) { return x + y; }类与对象
class Rectangle { public: int width, height; int area() { return width * height; } }; Rectangle rect; rect.width = 5; rect.height = 10;