全部笔记All notes

C++ 编程语言完整指南

阅读 14m 21s14m 21s read

概述

C++ 是一种高级、通用的编程语言,由 Bjarne Stroustrup 于 1979 年在贝尔实验室开始设计开发。C++ 是在 C 语言基础上发展而来的面向对象编程语言,兼具高性能和灵活性,被广泛应用于系统软件、游戏开发、嵌入式系统等领域。

核心特性

  • 多范式编程: 支持面向过程、面向对象、泛型编程
  • 高性能: 接近汇编语言的执行效率
  • 跨平台: 支持 Windows、macOS、Linux 等主流操作系统
  • 丰富的标准库: STL 提供了强大的数据结构和算法
  • 内存控制: 提供精确的内存管理机制
  • 向下兼容: 几乎完全兼容 C 语言

版本演进

版本发布年份主要特性使用场景
C++981998标准化,STL基础系统开发
C++032003Bug修复,小幅改进稳定项目
C++112011自动类型推导,Lambda,智能指针现代C++开发
C++142014泛型Lambda,变量模板模板编程
C++172017结构化绑定,并行算法高性能计算
C++202020概念,模块,协程大型项目
C++232023标准库扩展,性能优化现代应用

应用领域

领域描述典型应用
系统编程操作系统、驱动程序Linux内核模块、设备驱动
游戏开发高性能游戏引擎Unreal Engine、Unity
嵌入式系统IoT设备、单片机Arduino、树莓派项目
科学计算数值计算、仿真MATLAB、Mathematica
金融软件高频交易、风险管理量化交易系统
数据库系统存储引擎、查询优化MySQL、PostgreSQL

💡 推荐: 学习现代C++(C++11及以后版本),掌握RAII、智能指针等现代特性。


环境准备

系统要求

操作系统最低版本推荐版本架构支持
Windows7+10+x86, x64
macOS10.12+12+x86_64, ARM64
Linux任意发行版Ubuntu 20.04+x86_64, ARM64

开发工具选择

集成开发环境 (IDE)

IDE平台特点适用场景
CLion跨平台智能代码补全、强大调试专业开发
Visual StudioWindows微软官方、调试强大Windows开发
Qt Creator跨平台GUI开发友好桌面应用
Dev-C++Windows轻量级、适合入门学习使用
Code::Blocks跨平台开源免费教学环境

轻量级编辑器

编辑器特点扩展能力推荐度
VS Code轻量、插件丰富插件生态完善⭐⭐⭐⭐⭐
Sublime Text快速、美观插件支持⭐⭐⭐⭐
Vim/Neovim终端编辑器高度可定制⭐⭐⭐⭐
Emacs功能强大无限扩展⭐⭐⭐

在线开发环境

# 在线C++编译器和IDE
1. Replit: https://replit.com/languages/cpp
2. OnlineGDB: https://www.onlinegdb.com/online_c++_compiler
3. Compiler Explorer: https://godbolt.org/
4. Coliru: http://coliru.stacked-crooked.com/

编译器安装

Windows 环境

方案一:安装 Visual Studio

  1. 下载 Visual Studio Community(免费版)
  2. 选择工作负载:
    • 使用 C++ 的桌面开发
    • 使用 C++ 的游戏开发(可选)
  3. 安装组件:
    • MSVC v143 编译器
    • Windows 10/11 SDK
    • CMake 工具

方案二:安装 MinGW-w64

# 使用 MSYS2 安装
# 1. 下载并安装 MSYS2: https://www.msys2.org/
# 2. 更新包管理器
pacman -Syu

# 3. 安装编译工具链
pacman -S mingw-w64-x86_64-gcc
pacman -S mingw-w64-x86_64-gdb
pacman -S mingw-w64-x86_64-make
pacman -S mingw-w64-x86_64-cmake

# 4. 添加到系统PATH
# 添加 C:\msys64\mingw64\bin 到环境变量

macOS 环境

# 方案一:安装 Xcode Command Line Tools
xcode-select --install

# 方案二:使用 Homebrew 安装 GCC
brew install gcc
brew install cmake
brew install llvm

# 验证安装
g++ --version
clang++ --version

Linux 环境

# Ubuntu/Debian
sudo apt update
sudo apt install build-essential
sudo apt install g++ gdb make cmake
sudo apt install clang llvm

# CentOS/RHEL
sudo yum groupinstall "Development Tools"
sudo yum install gcc-c++ gdb cmake

# Arch Linux
sudo pacman -S base-devel
sudo pacman -S gcc gdb cmake

# 验证安装
g++ --version
gdb --version
cmake --version

编译器版本选择

# 检查编译器支持的C++标准
g++ -v
clang++ -v

# 编译时指定C++标准
g++ -std=c++11 program.cpp
g++ -std=c++14 program.cpp
g++ -std=c++17 program.cpp
g++ -std=c++20 program.cpp

语法基础

Hello World 程序

基本结构

#include <iostream>     // 包含输入输出流库
using namespace std;    // 使用标准命名空间

int main() {           // 主函数入口
    cout << "Hello, World!" << endl;  // 输出文本
    return 0;          // 返回0表示程序正常结束
}

详细解释

// 预处理指令 - 包含头文件
#include <iostream>   // 标准输入输出流
#include <string>     // 字符串处理
#include <vector>     // 动态数组
#include <algorithm>  // 算法库

// 命名空间
using namespace std;  // 使用标准命名空间
// 或者使用具体的标识符
// using std::cout;
// using std::endl;

// 函数声明
void displayMessage();
int add(int a, int b);

// 主函数
int main() {
    // 变量声明和初始化
    string name = "C++";
    int version = 20;
    
    // 输出操作
    cout << "欢迎学习 " << name << version << "!" << endl;
    
    // 函数调用
    displayMessage();
    int result = add(10, 20);
    cout << "计算结果: " << result << endl;
    
    return 0;
}

// 函数定义
void displayMessage() {
    cout << "这是一个函数调用示例" << endl;
}

int add(int a, int b) {
    return a + b;
}

编译和运行

基本编译

# 编译单个文件
g++ hello.cpp -o hello

# 运行程序
./hello                    # Linux/macOS
hello.exe                  # Windows

# 编译时指定C++标准
g++ -std=c++17 hello.cpp -o hello

# 开启所有警告
g++ -Wall -Wextra hello.cpp -o hello

# 调试版本
g++ -g -O0 hello.cpp -o hello_debug

# 发布版本
g++ -O2 -DNDEBUG hello.cpp -o hello_release

多文件编译

# 编译多个源文件
g++ main.cpp utils.cpp math.cpp -o program

# 分步编译
g++ -c main.cpp -o main.o
g++ -c utils.cpp -o utils.o
g++ -c math.cpp -o math.o
g++ main.o utils.o math.o -o program

# 使用 Makefile
make
make clean
make install

程序结构

标准项目结构

MyProject/
├── src/                    # 源代码目录
│   ├── main.cpp           # 主程序文件
│   ├── utils.cpp          # 工具函数实现
│   └── math.cpp           # 数学函数实现
├── include/               # 头文件目录
│   ├── utils.h           # 工具函数声明
│   └── math.h            # 数学函数声明
├── build/                 # 编译输出目录
├── docs/                  # 文档目录
├── tests/                 # 测试代码目录
├── CMakeLists.txt         # CMake配置文件
├── Makefile              # Make配置文件
└── README.md             # 项目说明文档

CMake 配置示例

# CMakeLists.txt
cmake_minimum_required(VERSION 3.10)

# 项目信息
project(MyProject VERSION 1.0)

# 设置C++标准
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# 包含头文件目录
include_directories(include)

# 源文件
set(SOURCES
    src/main.cpp
    src/utils.cpp
    src/math.cpp
)

# 生成可执行文件
add_executable(${PROJECT_NAME} ${SOURCES})

# 编译选项
target_compile_options(${PROJECT_NAME} PRIVATE
    -Wall -Wextra -O2
)

# 链接库(如果需要)
# target_link_libraries(${PROJECT_NAME} pthread)

数据类型和变量

基本数据类型

整数类型

#include <iostream>
#include <limits>
using namespace std;

int main() {
    // 基本整数类型
    char c = 'A';              // 字符,通常1字节
    short s = 32767;           // 短整型,通常2字节
    int i = 2147483647;        // 整型,通常4字节
    long l = 2147483647L;      // 长整型,至少4字节
    long long ll = 9223372036854775807LL;  // 长长整型,至少8字节
    
    // 无符号类型
    unsigned char uc = 255;    // 无符号字符
    unsigned short us = 65535; // 无符号短整型
    unsigned int ui = 4294967295U;  // 无符号整型
    unsigned long ul = 4294967295UL; // 无符号长整型
    unsigned long long ull = 18446744073709551615ULL; // 无符号长长整型
    
    // 输出各类型的大小和范围
    cout << "=== 整数类型信息 ===" << endl;
    cout << "char: " << sizeof(char) << " 字节, 范围: [" 
         << (int)numeric_limits<char>::min() << ", " 
         << (int)numeric_limits<char>::max() << "]" << endl;
    
    cout << "int: " << sizeof(int) << " 字节, 范围: [" 
         << numeric_limits<int>::min() << ", " 
         << numeric_limits<int>::max() << "]" << endl;
    
    cout << "long long: " << sizeof(long long) << " 字节, 范围: [" 
         << numeric_limits<long long>::min() << ", " 
         << numeric_limits<long long>::max() << "]" << endl;
    
    return 0;
}

浮点数类型

#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;

int main() {
    // 浮点数类型
    float f = 3.14159f;        // 单精度,通常4字节
    double d = 3.141592653589793;  // 双精度,通常8字节
    long double ld = 3.141592653589793238L; // 扩展精度
    
    // 科学计数法
    double scientific = 1.23e-4;  // 0.000123
    double large = 6.022e23;      // 阿伏伽德罗常数
    
    // 输出浮点数信息
    cout << fixed << setprecision(15);
    cout << "=== 浮点数类型信息 ===" << endl;
    cout << "float: " << sizeof(float) << " 字节, 精度: " 
         << numeric_limits<float>::digits10 << " 位" << endl;
    cout << "float 值: " << f << endl;
    
    cout << "double: " << sizeof(double) << " 字节, 精度: " 
         << numeric_limits<double>::digits10 << " 位" << endl;
    cout << "double 值: " << d << endl;
    
    cout << "long double: " << sizeof(long double) << " 字节, 精度: " 
         << numeric_limits<long double>::digits10 << " 位" << endl;
    cout << "long double 值: " << ld << endl;
    
    return 0;
}

布尔和字符类型

#include <iostream>
using namespace std;

int main() {
    // 布尔类型
    bool flag = true;
    bool result = false;
    
    cout << "=== 布尔类型 ===" << endl;
    cout << "bool 大小: " << sizeof(bool) << " 字节" << endl;
    cout << "true: " << flag << ", false: " << result << endl;
    cout << boolalpha;  // 以true/false形式输出
    cout << "true: " << flag << ", false: " << result << endl;
    
    // 字符类型
    char ch = 'A';
    char digit = '9';
    char newline = '\n';
    char tab = '\t';
    
    cout << "\n=== 字符类型 ===" << endl;
    cout << "字符: " << ch << ", ASCII值: " << (int)ch << endl;
    cout << "数字字符: " << digit << ", ASCII值: " << (int)digit << endl;
    
    // 宽字符类型
    wchar_t wide_char = L'中';
    char16_t utf16_char = u'A';
    char32_t utf32_char = U'🌟';
    
    cout << "宽字符大小: " << sizeof(wchar_t) << " 字节" << endl;
    cout << "UTF-16字符大小: " << sizeof(char16_t) << " 字节" << endl;
    cout << "UTF-32字符大小: " << sizeof(char32_t) << " 字节" << endl;
    
    return 0;
}

变量声明和初始化

变量声明方式

#include <iostream>
#include <string>
using namespace std;

int main() {
    // 基本声明
    int a;              // 声明但未初始化(包含垃圾值)
    int b = 10;         // 声明并初始化
    int c(20);          // 构造函数式初始化
    int d{30};          // 列表初始化(C++11)
    
    // 多变量声明
    int x = 1, y = 2, z = 3;
    
    // 自动类型推导(C++11)
    auto num = 42;          // 推导为 int
    auto pi = 3.14159;      // 推导为 double
    auto name = "C++";      // 推导为 const char*
    auto str = string("Hello"); // 推导为 string
    
    // 常量声明
    const int MAX_SIZE = 100;      // 编译时常量
    const string GREETING = "Hello"; // 常量字符串
    
    // C++11 constexpr
    constexpr int BUFFER_SIZE = 1024;  // 编译时常量表达式
    constexpr double CIRCLE_PI = 3.14159; // 编译时计算
    
    // 输出变量信息
    cout << "=== 变量值 ===" << endl;
    cout << "b: " << b << ", c: " << c << ", d: " << d << endl;
    cout << "自动推导 - num: " << num << ", pi: " << pi << endl;
    cout << "常量 - MAX_SIZE: " << MAX_SIZE << ", GREETING: " << GREETING << endl;
    
    return 0;
}

变量作用域

#include <iostream>
using namespace std;

// 全局变量
int global_var = 100;
const int GLOBAL_CONST = 200;

void function_scope_demo() {
    int local_var = 300;  // 局部变量
    cout << "函数内局部变量: " << local_var << endl;
    cout << "函数内访问全局变量: " << global_var << endl;
    
    // 静态局部变量
    static int static_var = 0;
    static_var++;
    cout << "静态变量值: " << static_var << endl;
}

int main() {
    cout << "=== 变量作用域演示 ===" << endl;
    
    // 块作用域
    {
        int block_var = 400;
        cout << "块内变量: " << block_var << endl;
        
        // 可以访问外层作用域的变量
        cout << "块内访问全局变量: " << global_var << endl;
    }
    // cout << block_var; // 错误!块外无法访问
    
    // 函数调用展示作用域
    function_scope_demo();
    function_scope_demo();
    function_scope_demo();
    
    // 变量遮蔽
    int global_var = 500;  // 局部变量遮蔽同名全局变量
    cout << "局部遮蔽后的变量: " << global_var << endl;
    cout << "使用::访问全局变量: " << ::global_var << endl;
    
    return 0;
}

类型转换

隐式类型转换

#include <iostream>
using namespace std;

int main() {
    cout << "=== 隐式类型转换 ===" << endl;
    
    // 算术转换
    int i = 42;
    double d = 3.14;
    auto result = i + d;  // int转换为double
    cout << "int + double = " << result << " (类型: double)" << endl;
    
    // 整数提升
    char c = 'A';
    short s = 100;
    auto sum = c + s;     // char和short都提升为int
    cout << "char + short = " << sum << " (类型: int)" << endl;
    
    // 数组到指针的转换
    int arr[5] = {1, 2, 3, 4, 5};
    int* ptr = arr;       // 数组名转换为指向首元素的指针
    cout << "数组首元素: " << *ptr << endl;
    
    // 函数到函数指针的转换
    void (*func_ptr)() = nullptr;
    
    return 0;
}

显式类型转换

#include <iostream>
using namespace std;

int main() {
    cout << "=== 显式类型转换 ===" << endl;
    
    // C风格转换(不推荐)
    double d = 3.14159;
    int i1 = (int)d;
    cout << "C风格转换: " << i1 << endl;
    
    // static_cast - 编译时类型转换
    int i2 = static_cast<int>(d);
    cout << "static_cast: " << i2 << endl;
    
    // dynamic_cast - 运行时类型转换(主要用于多态)
    // 示例需要多态类
    
    // const_cast - 移除const属性
    const int const_val = 100;
    int* non_const_ptr = const_cast<int*>(&const_val);
    // *non_const_ptr = 200; // 危险操作,未定义行为
    
    // reinterpret_cast - 重新解释内存内容
    int num = 0x41424344;
    char* char_ptr = reinterpret_cast<char*>(&num);
    cout << "重新解释为字符: ";
    for (int i = 0; i < 4; ++i) {
        cout << char_ptr[i];
    }
    cout << endl;
    
    return 0;
}

运算符系统

C++ 提供了丰富的运算符,用于执行各种数学运算、逻辑运算和位运算。

算术运算符

基本算术运算

#include <iostream>
using namespace std;

int main() {
    cout << "=== 算术运算符 ===" << endl;
    
    int a = 10, b = 3;
    double x = 10.0, y = 3.0;
    
    // 加法
    cout << "加法: " << a << " + " << b << " = " << (a + b) << endl;
    
    // 减法
    cout << "减法: " << a << " - " << b << " = " << (a - b) << endl;
    
    // 乘法
    cout << "乘法: " << a << " * " << b << " = " << (a * b) << endl;
    
    // 除法(整数除法)
    cout << "整数除法: " << a << " / " << b << " = " << (a / b) << endl;
    cout << "浮点除法: " << x << " / " << y << " = " << (x / y) << endl;
    
    // 取模
    cout << "取模: " << a << " % " << b << " = " << (a % b) << endl;
    
    // 注意:取模运算只能用于整数
    // cout << x % y;  // 错误!
    
    return 0;
}

自增自减运算符

#include <iostream>
using namespace std;

int main() {
    cout << "=== 自增自减运算符 ===" << endl;
    
    int a = 5;
    
    // 前缀自增:先增加,后返回值
    cout << "a = " << a << endl;
    cout << "++a = " << ++a << endl;  // a变为6,返回6
    cout << "a = " << a << endl;
    
    // 后缀自增:先返回值,后增加
    cout << "a++ = " << a++ << endl;  // 返回6,a变为7
    cout << "a = " << a << endl;
    
    // 前缀自减:先减少,后返回值
    cout << "--a = " << --a << endl;  // a变为6,返回6
    cout << "a = " << a << endl;
    
    // 后缀自减:先返回值,后减少
    cout << "a-- = " << a-- << endl;  // 返回6,a变为5
    cout << "a = " << a << endl;
    
    // 复合示例
    int x = 10, y = 20;
    int result = ++x + y--;  // x先增加为11,y先使用20后减为19
    cout << "++x + y-- = " << result << endl;  // 31
    cout << "x = " << x << ", y = " << y << endl;  // x=11, y=19
    
    return 0;
}

赋值运算符

复合赋值运算符

#include <iostream>
using namespace std;

int main() {
    cout << "=== 复合赋值运算符 ===" << endl;
    
    int a = 10;
    
    cout << "初始值: a = " << a << endl;
    
    // 加法赋值
    a += 5;  // 等价于 a = a + 5
    cout << "a += 5: a = " << a << endl;
    
    // 减法赋值
    a -= 3;  // 等价于 a = a - 3
    cout << "a -= 3: a = " << a << endl;
    
    // 乘法赋值
    a *= 2;  // 等价于 a = a * 2
    cout << "a *= 2: a = " << a << endl;
    
    // 除法赋值
    a /= 4;  // 等价于 a = a / 4
    cout << "a /= 4: a = " << a << endl;
    
    // 取模赋值
    a %= 3;  // 等价于 a = a % 3
    cout << "a %= 3: a = " << a << endl;
    
    // 位运算赋值
    int b = 12;  // 二进制: 1100
    cout << "初始值: b = " << b << " (二进制: 1100)" << endl;
    
    b <<= 2;  // 左移2位
    cout << "b <<= 2: b = " << b << " (二进制: 110000)" << endl;
    
    b >>= 1;  // 右移1位
    cout << "b >>= 1: b = " << b << " (二进制: 11000)" << endl;
    
    return 0;
}

比较运算符

#include <iostream>
using namespace std;

int main() {
    cout << "=== 比较运算符 ===" << endl;
    
    int a = 10, b = 20, c = 10;
    
    cout << "a = " << a << ", b = " << b << ", c = " << c << endl;
    
    // 相等比较
    cout << "a == b: " << (a == b) << endl;  // 0 (false)
    cout << "a == c: " << (a == c) << endl;  // 1 (true)
    
    // 不等比较
    cout << "a != b: " << (a != b) << endl;  // 1 (true)
    cout << "a != c: " << (a != c) << endl;  // 0 (false)
    
    // 大小比较
    cout << "a < b: " << (a < b) << endl;    // 1 (true)
    cout << "a > b: " << (a > b) << endl;    // 0 (false)
    cout << "a <= c: " << (a <= c) << endl;  // 1 (true)
    cout << "a >= c: " << (a >= c) << endl;  // 1 (true)
    
    // 字符串比较
    string str1 = "apple";
    string str2 = "banana";
    string str3 = "apple";
    
    cout << "\n字符串比较:" << endl;
    cout << "str1 = \"" << str1 << "\", str2 = \"" << str2 << "\"" << endl;
    cout << "str1 == str2: " << (str1 == str2) << endl;  // 0
    cout << "str1 == str3: " << (str1 == str3) << endl;  // 1
    cout << "str1 < str2: " << (str1 < str2) << endl;    // 1 (字典序)
    
    return 0;
}

逻辑运算符

#include <iostream>
using namespace std;

int main() {
    cout << "=== 逻辑运算符 ===" << endl;
    
    bool a = true, b = false, c = true;
    
    cout << "a = " << a << ", b = " << b << ", c = " << c << endl;
    
    // 逻辑与 (AND)
    cout << "a && b: " << (a && b) << endl;  // 0 (false)
    cout << "a && c: " << (a && c) << endl;  // 1 (true)
    
    // 逻辑或 (OR)
    cout << "a || b: " << (a || b) << endl;  // 1 (true)
    cout << "b || false: " << (b || false) << endl;  // 0 (false)
    
    // 逻辑非 (NOT)
    cout << "!a: " << !a << endl;  // 0 (false)
    cout << "!b: " << !b << endl;  // 1 (true)
    
    // 短路求值演示
    int x = 5, y = 0;
    cout << "\n短路求值演示:" << endl;
    
    // 逻辑与短路:如果第一个为false,不会评估第二个
    if (y != 0 && x / y > 2) {
        cout << "条件成立" << endl;
    } else {
        cout << "条件不成立(避免了除零错误)" << endl;
    }
    
    // 逻辑或短路:如果第一个为true,不会评估第二个
    if (x > 0 || x / y > 2) {
        cout << "条件成立(避免了除零错误)" << endl;
    }
    
    return 0;
}

位运算符

基本位运算

#include <iostream>
#include <bitset>
using namespace std;

int main() {
    cout << "=== 位运算符 ===" << endl;
    
    unsigned int a = 12;  // 二进制: 1100
    unsigned int b = 10;  // 二进制: 1010
    
    cout << "a = " << a << " (二进制: " << bitset<8>(a) << ")" << endl;
    cout << "b = " << b << " (二进制: " << bitset<8>(b) << ")" << endl;
    
    // 按位与 (AND)
    unsigned int and_result = a & b;  // 1100 & 1010 = 1000
    cout << "a & b = " << and_result << " (二进制: " << bitset<8>(and_result) << ")" << endl;
    
    // 按位或 (OR)
    unsigned int or_result = a | b;   // 1100 | 1010 = 1110
    cout << "a | b = " << or_result << " (二进制: " << bitset<8>(or_result) << ")" << endl;
    
    // 按位异或 (XOR)
    unsigned int xor_result = a ^ b;  // 1100 ^ 1010 = 0110
    cout << "a ^ b = " << xor_result << " (二进制: " << bitset<8>(xor_result) << ")" << endl;
    
    // 按位取反 (NOT)
    unsigned int not_a = ~a;
    cout << "~a = " << not_a << " (二进制: " << bitset<8>(not_a) << ")" << endl;
    
    // 左移
    unsigned int left_shift = a << 2;  // 1100 << 2 = 110000
    cout << "a << 2 = " << left_shift << " (二进制: " << bitset<8>(left_shift) << ")" << endl;
    
    // 右移
    unsigned int right_shift = a >> 1;  // 1100 >> 1 = 0110
    cout << "a >> 1 = " << right_shift << " (二进制: " << bitset<8>(right_shift) << ")" << endl;
    
    return 0;
}

位运算实际应用

#include <iostream>
#include <bitset>
using namespace std;

int main() {
    cout << "=== 位运算实际应用 ===" << endl;
    
    // 权限管理系统
    const unsigned int READ = 1;    // 0001
    const unsigned int WRITE = 2;   // 0010
    const unsigned int EXECUTE = 4; // 0100
    const unsigned int DELETE = 8;  // 1000
    
    // 设置权限
    unsigned int permissions = 0;
    permissions |= READ;    // 添加读权限
    permissions |= WRITE;   // 添加写权限
    permissions |= EXECUTE; // 添加执行权限
    
    cout << "当前权限: " << bitset<4>(permissions) << endl;
    
    // 检查权限
    if (permissions & READ) {
        cout << "具有读权限" << endl;
    }
    if (permissions & WRITE) {
        cout << "具有写权限" << endl;
    }
    if (!(permissions & DELETE)) {
        cout << "没有删除权限" << endl;
    }
    
    // 移除权限
    permissions &= ~WRITE;  // 移除写权限
    cout << "移除写权限后: " << bitset<4>(permissions) << endl;
    
    // 切换权限
    permissions ^= EXECUTE;  // 切换执行权限
    cout << "切换执行权限后: " << bitset<4>(permissions) << endl;
    
    // 快速计算(位运算技巧)
    cout << "\n=== 位运算技巧 ===" << endl;
    
    int n = 16;
    
    // 判断是否为2的幂
    bool isPowerOfTwo = (n & (n - 1)) == 0;
    cout << n << " 是否为2的幂: " << isPowerOfTwo << endl;
    
    // 快速乘以2的幂
    cout << n << " * 8 = " << (n << 3) << endl;  // 左移3位相当于乘以8
    
    // 快速除以2的幂
    cout << n << " / 4 = " << (n >> 2) << endl;  // 右移2位相当于除以4
    
    // 交换两个数(不使用临时变量)
    int x = 5, y = 10;
    cout << "交换前: x = " << x << ", y = " << y << endl;
    x ^= y;
    y ^= x;
    x ^= y;
    cout << "交换后: x = " << x << ", y = " << y << endl;
    
    return 0;
}

条件运算符(三元运算符)

#include <iostream>
using namespace std;

int main() {
    cout << "=== 条件运算符 ===" << endl;
    
    int a = 10, b = 20;
    
    // 基本语法:condition ? value_if_true : value_if_false
    int max_value = (a > b) ? a : b;
    cout << "较大值: " << max_value << endl;
    
    // 用于输出不同内容
    cout << "a " << ((a > b) ? "大于" : "小于等于") << " b" << endl;
    
    // 嵌套条件运算符
    int score = 85;
    string grade = (score >= 90) ? "A" : 
                   (score >= 80) ? "B" : 
                   (score >= 70) ? "C" : 
                   (score >= 60) ? "D" : "F";
    cout << "分数 " << score << " 对应等级: " << grade << endl;
    
    // 在函数调用中使用
    int x = 5, y = -3;
    int abs_y = (y >= 0) ? y : -y;
    cout << "y 的绝对值: " << abs_y << endl;
    
    // 条件运算符的返回值类型
    int num = 10;
    double pi = 3.14;
    auto result = (num > 5) ? num : pi;  // result类型为double
    cout << "result = " << result << endl;
    
    return 0;
}

运算符优先级

#include <iostream>
using namespace std;

int main() {
    cout << "=== 运算符优先级演示 ===" << endl;
    
    int a = 2, b = 3, c = 4, d = 5;
    
    // 算术运算符优先级
    int result1 = a + b * c;  // 等价于 a + (b * c)
    cout << "a + b * c = " << result1 << " (等价于 " << a << " + (" << b << " * " << c << "))" << endl;
    
    int result2 = (a + b) * c;  // 使用括号改变优先级
    cout << "(a + b) * c = " << result2 << endl;
    
    // 关系和逻辑运算符
    bool result3 = a < b && c > d;  // 等价于 (a < b) && (c > d)
    cout << "a < b && c > d = " << result3 << endl;
    
    // 赋值和其他运算符
    int x = 1;
    int result4 = x += a * b;  // 等价于 x = x + (a * b)
    cout << "x += a * b, x = " << x << ", result = " << result4 << endl;
    
    // 复杂表达式
    bool complex = a > 0 && b + c * d > 10 || a == 1;
    cout << "复杂表达式结果: " << complex << endl;
    
    // 推荐:使用括号明确表达意图
    bool clear = (a > 0) && ((b + c * d) > 10) || (a == 1);
    cout << "清晰表达式结果: " << clear << endl;
    
    cout << "\n=== 运算符优先级表(从高到低)===" << endl;
    cout << "1. () [] -> .                  (最高)" << endl;
    cout << "2. ! ~ ++ -- + - * &          (一元运算符)" << endl;
    cout << "3. * / %                      (乘除取模)" << endl;
    cout << "4. + -                        (加减)" << endl;
    cout << "5. << >>                      (位移)" << endl;
    cout << "6. < <= > >=                  (关系)" << endl;
    cout << "7. == !=                      (相等)" << endl;
    cout << "8. &                          (位与)" << endl;
    cout << "9. ^                          (位异或)" << endl;
    cout << "10. |                         (位或)" << endl;
    cout << "11. &&                        (逻辑与)" << endl;
    cout << "12. ||                        (逻辑或)" << endl;
    cout << "13. ?:                        (条件)" << endl;
    cout << "14. = += -= *= /= %=          (赋值)" << endl;
    cout << "15. ,                         (逗号,最低)" << endl;
    
    return 0;
}

流程控制

C++ 提供了丰富的流程控制语句,用于控制程序的执行顺序。

条件判断

if 语句

#include <iostream>
using namespace std;

int main() {
    cout << "=== if 条件判断 ===" << endl;
    
    int age = 18;
    
    // 基本 if 语句
    if (age >= 18) {
        cout << "您已成年,可以投票" << endl;
    }
    
    // if-else 语句
    int score = 85;
    if (score >= 60) {
        cout << "考试及格,分数: " << score << endl;
    } else {
        cout << "考试不及格,分数: " << score << endl;
    }
    
    // if-else if-else 多分支判断
    if (score >= 90) {
        cout << "等级: A (优秀)" << endl;
    } else if (score >= 80) {
        cout << "等级: B (良好)" << endl;
    } else if (score >= 70) {
        cout << "等级: C (中等)" << endl;
    } else if (score >= 60) {
        cout << "等级: D (及格)" << endl;
    } else {
        cout << "等级: F (不及格)" << endl;
    }
    
    // 嵌套 if 语句
    bool hasLicense = true;
    int drivingAge = 20;
    
    if (drivingAge >= 18) {
        if (hasLicense) {
            cout << "可以开车" << endl;
        } else {
            cout << "年龄够了,但需要驾照" << endl;
        }
    } else {
        cout << "年龄不够,不能开车" << endl;
    }
    
    return 0;
}

switch 语句

#include <iostream>
using namespace std;

int main() {
    cout << "=== switch 多分支选择 ===" << endl;
    
    int day = 3;
    
    // 基本 switch 语句
    switch (day) {
        case 1:
            cout << "星期一" << endl;
            break;
        case 2:
            cout << "星期二" << endl;
            break;
        case 3:
            cout << "星期三" << endl;
            break;
        case 4:
            cout << "星期四" << endl;
            break;
        case 5:
            cout << "星期五" << endl;
            break;
        case 6:
            cout << "星期六" << endl;
            break;
        case 7:
            cout << "星期日" << endl;
            break;
        default:
            cout << "无效的日期" << endl;
            break;
    }
    
    // switch 语句的贯穿特性
    char grade = 'B';
    cout << "成绩等级 " << grade << " 的评价: ";
    switch (grade) {
        case 'A':
        case 'a':
            cout << "优秀!继续保持!" << endl;
            break;
        case 'B':
        case 'b':
            cout << "良好!还有提升空间!" << endl;
            break;
        case 'C':
        case 'c':
            cout << "及格,需要努力!" << endl;
            break;
        case 'D':
        case 'd':
        case 'F':
        case 'f':
            cout << "不及格,必须重修!" << endl;
            break;
        default:
            cout << "无效的等级" << endl;
            break;
    }
    
    // 实际应用:简单计算器
    double num1 = 10.0, num2 = 3.0;
    char operation = '+';
    
    cout << "\n计算器示例: " << num1 << " " << operation << " " << num2 << " = ";
    switch (operation) {
        case '+':
            cout << (num1 + num2) << endl;
            break;
        case '-':
            cout << (num1 - num2) << endl;
            break;
        case '*':
            cout << (num1 * num2) << endl;
            break;
        case '/':
            if (num2 != 0) {
                cout << (num1 / num2) << endl;
            } else {
                cout << "错误:除数不能为零!" << endl;
            }
            break;
        default:
            cout << "错误:不支持的运算符!" << endl;
            break;
    }
    
    return 0;
}

循环语句

for 循环

#include <iostream>
using namespace std;

int main() {
    cout << "=== for 循环 ===" << endl;
    
    // 基本 for 循环
    cout << "1-10 的数字: ";
    for (int i = 1; i <= 10; i++) {
        cout << i << " ";
    }
    cout << endl;
    
    // 不同的步长
    cout << "1-20 的偶数: ";
    for (int i = 2; i <= 20; i += 2) {
        cout << i << " ";
    }
    cout << endl;
    
    // 倒序循环
    cout << "10-1 倒序: ";
    for (int i = 10; i >= 1; i--) {
        cout << i << " ";
    }
    cout << endl;
    
    // 嵌套循环:打印乘法表
    cout << "\n九九乘法表:" << endl;
    for (int i = 1; i <= 9; i++) {
        for (int j = 1; j <= i; j++) {
            cout << j << "×" << i << "=" << (i * j) << "\t";
        }
        cout << endl;
    }
    
    // 数组遍历
    int numbers[] = {2, 4, 6, 8, 10};
    int size = sizeof(numbers) / sizeof(numbers[0]);
    
    cout << "\n数组元素: ";
    for (int i = 0; i < size; i++) {
        cout << numbers[i] << " ";
    }
    cout << endl;
    
    // 范围 for 循环 (C++11)
    cout << "使用范围for循环: ";
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl;
    
    return 0;
}

while 循环

#include <iostream>
using namespace std;

int main() {
    cout << "=== while 循环 ===" << endl;
    
    // 基本 while 循环
    int count = 1;
    cout << "1-5 计数: ";
    while (count <= 5) {
        cout << count << " ";
        count++;
    }
    cout << endl;
    
    // 用户输入验证
    int number;
    cout << "\n请输入一个正数(输入负数退出): ";
    while (cin >> number && number >= 0) {
        cout << "您输入的数字是: " << number << endl;
        cout << "请再输入一个正数(输入负数退出): ";
    }
    cout << "程序结束" << endl;
    
    // 累加计算
    int sum = 0;
    int i = 1;
    while (i <= 100) {
        sum += i;
        i++;
    }
    cout << "1-100的和: " << sum << endl;
    
    // 阶乘计算
    int n = 5;
    long long factorial = 1;
    int temp = n;
    while (temp > 0) {
        factorial *= temp;
        temp--;
    }
    cout << n << "! = " << factorial << endl;
    
    return 0;
}

do-while 循环

#include <iostream>
using namespace std;

int main() {
    cout << "=== do-while 循环 ===" << endl;
    
    // 基本 do-while 循环
    int num = 1;
    cout << "do-while 示例: ";
    do {
        cout << num << " ";
        num++;
    } while (num <= 5);
    cout << endl;
    
    // 菜单驱动程序
    int choice;
    do {
        cout << "\n=== 菜单 ===" << endl;
        cout << "1. 显示当前时间" << endl;
        cout << "2. 计算圆面积" << endl;
        cout << "3. 温度转换" << endl;
        cout << "0. 退出程序" << endl;
        cout << "请选择操作 (0-3): ";
        cin >> choice;
        
        switch (choice) {
            case 1:
                cout << "当前时间功能(示例)" << endl;
                break;
            case 2: {
                double radius;
                cout << "请输入圆的半径: ";
                cin >> radius;
                cout << "圆的面积: " << (3.14159 * radius * radius) << endl;
                break;
            }
            case 3: {
                double celsius;
                cout << "请输入摄氏温度: ";
                cin >> celsius;
                cout << "华氏温度: " << (celsius * 9.0 / 5.0 + 32) << endl;
                break;
            }
            case 0:
                cout << "程序退出,再见!" << endl;
                break;
            default:
                cout << "无效选择,请重试!" << endl;
                break;
        }
    } while (choice != 0);
    
    return 0;
}

跳转语句

break 和 continue

#include <iostream>
using namespace std;

int main() {
    cout << "=== break 和 continue ===" << endl;
    
    // break 示例:提前跳出循环
    cout << "break 示例 - 找到第一个大于5的数字:" << endl;
    for (int i = 1; i <= 10; i++) {
        if (i > 5) {
            cout << "找到大于5的数字: " << i << endl;
            break;  // 跳出循环
        }
        cout << "当前数字: " << i << endl;
    }
    
    // continue 示例:跳过本次迭代
    cout << "\ncontinue 示例 - 只打印奇数:" << endl;
    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) {
            continue;  // 跳过偶数
        }
        cout << "奇数: " << i << endl;
    }
    
    // 嵌套循环中的 break
    cout << "\n嵌套循环中的 break:" << endl;
    for (int i = 1; i <= 3; i++) {
        cout << "外层循环 i = " << i << endl;
        for (int j = 1; j <= 5; j++) {
            if (j == 3) {
                cout << "  内层循环在 j = 3 时跳出" << endl;
                break;  // 只跳出内层循环
            }
            cout << "  内层循环 j = " << j << endl;
        }
    }
    
    // 使用标签跳出多层循环(goto)
    cout << "\n使用 goto 跳出多层循环:" << endl;
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            cout << "i = " << i << ", j = " << j << endl;
            if (i == 2 && j == 2) {
                cout << "跳出所有循环" << endl;
                goto end_loops;  // 跳转到标签
            }
        }
    }
    
    end_loops:
    cout << "所有循环结束" << endl;
    
    return 0;
}

goto 语句

#include <iostream>
using namespace std;

int main() {
    cout << "=== goto 语句 ===" << endl;
    
    int choice;
    
    // 使用 goto 实现简单的程序流程控制
    start:
    cout << "\n请选择操作:" << endl;
    cout << "1. 计算平方" << endl;
    cout << "2. 计算立方" << endl;
    cout << "3. 退出" << endl;
    cout << "输入选择 (1-3): ";
    cin >> choice;
    
    if (choice == 1) {
        int num;
        cout << "输入一个数字: ";
        cin >> num;
        cout << num << " 的平方是: " << (num * num) << endl;
        goto start;  // 返回菜单
    } else if (choice == 2) {
        int num;
        cout << "输入一个数字: ";
        cin >> num;
        cout << num << " 的立方是: " << (num * num * num) << endl;
        goto start;  // 返回菜单
    } else if (choice == 3) {
        goto end;  // 跳转到程序结束
    } else {
        cout << "无效选择,请重试!" << endl;
        goto start;  // 返回菜单
    }
    
    end:
    cout << "程序结束!" << endl;
    
    // 注意:goto 语句虽然可用,但现代C++编程中应该避免使用
    // 推荐使用结构化的控制语句(if、while、for等)
    
    return 0;
}

实际应用示例

质数判断程序

#include <iostream>
#include <cmath>
using namespace std;

bool isPrime(int n) {
    if (n <= 1) return false;
    if (n <= 3) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;
    
    for (int i = 5; i * i <= n; i += 6) {
        if (n % i == 0 || n % (i + 2) == 0) {
            return false;
        }
    }
    return true;
}

int main() {
    cout << "=== 质数判断程序 ===" << endl;
    
    int start, end;
    cout << "请输入范围 (开始 结束): ";
    cin >> start >> end;
    
    cout << start << " 到 " << end << " 之间的质数:" << endl;
    
    int count = 0;
    for (int i = start; i <= end; i++) {
        if (isPrime(i)) {
            cout << i << " ";
            count++;
            if (count % 10 == 0) {  // 每10个换行
                cout << endl;
            }
        }
    }
    
    cout << "\n共找到 " << count << " 个质数" << endl;
    
    return 0;
}

猜数字游戏

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
    cout << "=== 猜数字游戏 ===" << endl;
    
    // 初始化随机数生成器
    srand(static_cast<unsigned int>(time(nullptr)));
    
    bool playAgain = true;
    
    while (playAgain) {
        int target = rand() % 100 + 1;  // 1-100 的随机数
        int guess;
        int attempts = 0;
        const int maxAttempts = 7;
        
        cout << "\n我想了一个1到100之间的数字,你能猜中吗?" << endl;
        cout << "你有 " << maxAttempts << " 次机会!" << endl;
        
        bool won = false;
        while (attempts < maxAttempts && !won) {
            cout << "\n第 " << (attempts + 1) << " 次猜测: ";
            cin >> guess;
            attempts++;
            
            if (guess == target) {
                cout << "🎉 恭喜!你用 " << attempts << " 次就猜中了!" << endl;
                won = true;
            } else if (guess < target) {
                cout << "太小了!";
                if (attempts < maxAttempts) {
                    cout << " 还有 " << (maxAttempts - attempts) << " 次机会";
                }
                cout << endl;
            } else {
                cout << "太大了!";
                if (attempts < maxAttempts) {
                    cout << " 还有 " << (maxAttempts - attempts) << " 次机会";
                }
                cout << endl;
            }
        }
        
        if (!won) {
            cout << "\n😢 很遗憾,机会用完了!正确答案是 " << target << endl;
        }
        
        // 询问是否再玩一次
        char choice;
        cout << "\n要再玩一次吗?(y/n): ";
        cin >> choice;
        playAgain = (choice == 'y' || choice == 'Y');
    }
    
    cout << "谢谢游戏,再见!" << endl;
    
    return 0;
}

函数编程

函数是C++程序的基本组成单元,用于封装可重用的代码块。

函数基础

函数定义和声明

#include <iostream>
using namespace std;

// 函数声明
int add(int a, int b);                    // 加法函数
double calculateArea(double radius);       // 计算圆面积
void printMessage(string message);         // 无返回值函数
bool isPrime(int n);                      // 判断质数

// 函数定义
int add(int a, int b) {
    return a + b;
}

double calculateArea(double radius) {
    const double PI = 3.14159;
    return PI * radius * radius;
}

void printMessage(string message) {
    cout << "消息: " << message << endl;
}

bool isPrime(int n) {
    if (n <= 1) return false;
    if (n <= 3) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;
    
    for (int i = 5; i * i <= n; i += 6) {
        if (n % i == 0 || n % (i + 2) == 0) {
            return false;
        }
    }
    return true;
}

int main() {
    cout << "=== 函数基础 ===" << endl;
    
    // 调用函数
    int sum = add(10, 20);
    cout << "10 + 20 = " << sum << endl;
    
    double area = calculateArea(5.0);
    cout << "半径为5的圆的面积: " << area << endl;
    
    printMessage("Hello, Functions!");
    
    int number = 17;
    if (isPrime(number)) {
        cout << number << " 是质数" << endl;
    } else {
        cout << number << " 不是质数" << endl;
    }
    
    return 0;
}

参数传递方式

值传递、引用传递、指针传递

#include <iostream>
using namespace std;

// 值传递:传递参数的副本
void swapByValue(int a, int b) {
    cout << "交换前 (值传递): a = " << a << ", b = " << b << endl;
    int temp = a;
    a = b;
    b = temp;
    cout << "交换后 (值传递): a = " << a << ", b = " << b << endl;
}

// 引用传递:传递参数的引用
void swapByReference(int& a, int& b) {
    cout << "交换前 (引用传递): a = " << a << ", b = " << b << endl;
    int temp = a;
    a = b;
    b = temp;
    cout << "交换后 (引用传递): a = " << a << ", b = " << b << endl;
}

// 指针传递:传递参数的地址
void swapByPointer(int* a, int* b) {
    cout << "交换前 (指针传递): *a = " << *a << ", *b = " << *b << endl;
    int temp = *a;
    *a = *b;
    *b = temp;
    cout << "交换后 (指针传递): *a = " << *a << ", *b = " << *b << endl;
}

// 常量引用传递:避免复制大对象
void printString(const string& str) {
    cout << "字符串内容: " << str << endl;
    // str += "test";  // 错误!不能修改常量引用
}

// 数组作为参数
void printArray(int arr[], int size) {
    cout << "数组元素: ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

// 等价的指针参数
void printArrayPtr(int* arr, int size) {
    cout << "数组元素 (指针版本): ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

int main() {
    cout << "=== 参数传递方式 ===" << endl;
    
    int x = 10, y = 20;
    
    cout << "\n原始值: x = " << x << ", y = " << y << endl;
    
    // 值传递:不会改变原始值
    swapByValue(x, y);
    cout << "值传递后: x = " << x << ", y = " << y << endl;
    
    // 引用传递:会改变原始值
    swapByReference(x, y);
    cout << "引用传递后: x = " << x << ", y = " << y << endl;
    
    // 重置值
    x = 10; y = 20;
    
    // 指针传递:会改变原始值
    swapByPointer(&x, &y);
    cout << "指针传递后: x = " << x << ", y = " << y << endl;
    
    // 常量引用传递
    string message = "Hello, World!";
    printString(message);
    
    // 数组参数
    int numbers[] = {1, 2, 3, 4, 5};
    int size = sizeof(numbers) / sizeof(numbers[0]);
    printArray(numbers, size);
    printArrayPtr(numbers, size);
    
    return 0;
}

函数重载

#include <iostream>
using namespace std;

// 函数重载:同名函数,不同参数
int add(int a, int b) {
    cout << "调用 int add(int, int)" << endl;
    return a + b;
}

double add(double a, double b) {
    cout << "调用 double add(double, double)" << endl;
    return a + b;
}

int add(int a, int b, int c) {
    cout << "调用 int add(int, int, int)" << endl;
    return a + b + c;
}

string add(const string& a, const string& b) {
    cout << "调用 string add(string, string)" << endl;
    return a + b;
}

// 重载的打印函数
void print(int value) {
    cout << "整数: " << value << endl;
}

void print(double value) {
    cout << "浮点数: " << value << endl;
}

void print(const string& value) {
    cout << "字符串: " << value << endl;
}

void print(char value) {
    cout << "字符: " << value << endl;
}

// 重载的计算函数
double calculate(double radius) {
    // 计算圆面积
    return 3.14159 * radius * radius;
}

double calculate(double length, double width) {
    // 计算矩形面积
    return length * width;
}

double calculate(double a, double b, double c) {
    // 计算三角形面积(海伦公式)
    double s = (a + b + c) / 2;
    return sqrt(s * (s - a) * (s - b) * (s - c));
}

int main() {
    cout << "=== 函数重载 ===" << endl;
    
    // 测试 add 函数重载
    cout << "\n=== add 函数重载 ===" << endl;
    cout << "结果: " << add(3, 5) << endl;              // 调用 int 版本
    cout << "结果: " << add(3.5, 2.1) << endl;          // 调用 double 版本
    cout << "结果: " << add(1, 2, 3) << endl;           // 调用三参数版本
    cout << "结果: " << add(string("Hello"), string(" World")) << endl;  // 调用 string 版本
    
    // 测试 print 函数重载
    cout << "\n=== print 函数重载 ===" << endl;
    print(42);          // 调用 int 版本
    print(3.14);        // 调用 double 版本
    print("Hello");     // 调用 string 版本
    print('A');         // 调用 char 版本
    
    // 测试 calculate 函数重载
    cout << "\n=== calculate 函数重载 ===" << endl;
    cout << "圆面积 (半径=5): " << calculate(5.0) << endl;
    cout << "矩形面积 (长=10, 宽=5): " << calculate(10.0, 5.0) << endl;
    cout << "三角形面积 (边长=3,4,5): " << calculate(3.0, 4.0, 5.0) << endl;
    
    return 0;
}

默认参数

#include <iostream>
using namespace std;

// 默认参数函数
void printInfo(string name, int age = 18, string city = "未知") {
    cout << "姓名: " << name << ", 年龄: " << age << ", 城市: " << city << endl;
}

// 计算矩形面积,默认为正方形
double rectangleArea(double length, double width = -1) {
    if (width == -1) {
        width = length;  // 默认为正方形
    }
    return length * width;
}

// 打印数组,默认分隔符
void printNumbers(int arr[], int size, string separator = ", ") {
    for (int i = 0; i < size; i++) {
        cout << arr[i];
        if (i < size - 1) {
            cout << separator;
        }
    }
    cout << endl;
}

// 银行利息计算
double calculateInterest(double principal, double rate = 0.03, int years = 1) {
    return principal * rate * years;
}

// 创建问候消息
string createGreeting(string name, string greeting = "Hello", string punctuation = "!") {
    return greeting + ", " + name + punctuation;
}

int main() {
    cout << "=== 默认参数 ===" << endl;
    
    // 测试 printInfo 函数
    cout << "\n=== 个人信息打印 ===" << endl;
    printInfo("张三");                           // 使用所有默认值
    printInfo("李四", 25);                       // 使用部分默认值
    printInfo("王五", 30, "北京");               // 不使用默认值
    
    // 测试矩形面积计算
    cout << "\n=== 矩形面积计算 ===" << endl;
    cout << "正方形面积 (边长=5): " << rectangleArea(5) << endl;
    cout << "矩形面积 (长=10, 宽=3): " << rectangleArea(10, 3) << endl;
    
    // 测试数组打印
    cout << "\n=== 数组打印 ===" << endl;
    int numbers[] = {1, 2, 3, 4, 5};
    int size = sizeof(numbers) / sizeof(numbers[0]);
    
    cout << "默认分隔符: ";
    printNumbers(numbers, size);
    
    cout << "自定义分隔符: ";
    printNumbers(numbers, size, " | ");
    
    cout << "无分隔符: ";
    printNumbers(numbers, size, "");
    
    // 测试利息计算
    cout << "\n=== 利息计算 ===" << endl;
    double principal = 10000;
    cout << "本金: " << principal << endl;
    cout << "默认利率和期限: " << calculateInterest(principal) << endl;
    cout << "指定利率 5%: " << calculateInterest(principal, 0.05) << endl;
    cout << "指定利率 4% 期限 3年: " << calculateInterest(principal, 0.04, 3) << endl;
    
    // 测试问候消息
    cout << "\n=== 问候消息 ===" << endl;
    cout << createGreeting("Alice") << endl;
    cout << createGreeting("Bob", "Hi") << endl;
    cout << createGreeting("Charlie", "Hey", "!!!") << endl;
    
    return 0;
}

内联函数

#include <iostream>
using namespace std;

// 内联函数:建议编译器在调用处直接展开函数代码
inline int max(int a, int b) {
    return (a > b) ? a : b;
}

inline int min(int a, int b) {
    return (a < b) ? a : b;
}

inline double square(double x) {
    return x * x;
}

inline double cube(double x) {
    return x * x * x;
}

// 内联函数适用于简单、频繁调用的函数
inline bool isEven(int n) {
    return (n % 2) == 0;
}

inline bool isOdd(int n) {
    return (n % 2) != 0;
}

// 复杂函数不适合内联
inline double complexCalculation(double x) {
    // 编译器可能忽略内联建议
    double result = 0;
    for (int i = 0; i < 1000; i++) {
        result += sin(x) * cos(x) * tan(x);
    }
    return result;
}

int main() {
    cout << "=== 内联函数 ===" << endl;
    
    int a = 10, b = 20;
    
    cout << "a = " << a << ", b = " << b << endl;
    cout << "max(a, b) = " << max(a, b) << endl;
    cout << "min(a, b) = " << min(a, b) << endl;
    
    double x = 5.0;
    cout << "\nx = " << x << endl;
    cout << "square(x) = " << square(x) << endl;
    cout << "cube(x) = " << cube(x) << endl;
    
    cout << "\n奇偶性判断:" << endl;
    for (int i = 1; i <= 5; i++) {
        cout << i << " 是" << (isEven(i) ? "偶数" : "奇数") << endl;
    }
    
    // 内联函数的优势:
    // 1. 减少函数调用开销
    // 2. 提高程序执行效率
    // 3. 保持代码的模块化
    
    // 注意事项:
    // 1. 编译器决定是否真正内联
    // 2. 复杂函数不适合内联
    // 3. 递归函数通常不会内联
    
    return 0;
}

相关文章

C++ 进阶主题

  • C++ STL 标准模板库 - 容器、算法与迭代器
  • C++ 面向对象编程 - 类、继承与多态
  • C++ 模板编程 - 泛型编程技术
  • C++ 智能指针 - 现代内存管理

系统编程

  • 常用Linux命令 - Linux 环境开发
  • 多线程编程 - 并发与同步
  • 网络编程 - Socket 编程
  • 内存管理 - 动态内存分配

语言对比学习

性能优化

  • C++ 性能优化 - 优化技巧
  • 编译器优化 - 编译选项
  • 内存优化 - 减少内存使用
  • 算法优化 - 高效算法

开发工具

项目实战

  • GDB 调试器 - 程序调试技术
  • Valgrind 内存检测 - 内存泄漏检测

相关语言对比

最佳实践

  • 编码规范 - 代码风格指南
  • 异常处理 - 错误处理机制
  • 单元测试 - 测试框架使用
  • 设计模式 - 常用设计模式