1. Hello World
1 2 3 4 5 #include <iostream> int main () { std::cout << "Hello, World!" << std::endl; return 0 ; }
2. 变量与数据类型
1 2 3 4 5 6 7 8 9 #include <iostream> int main () { int a = 10 ; double b = 3.14 ; char c = 'A' ; bool d = true ; std::cout << a << " " << b << " " << c << " " << d << std::endl; return 0 ; }
3. 条件语句(if/else, switch)
1 2 3 4 5 6 7 8 9 10 11 12 13 #include <iostream> int main () { int x = 5 ; if (x > 0 ) std::cout << "Positive\n" ; else if (x < 0 ) std::cout << "Negative\n" ; else std::cout << "Zero\n" ; switch (x) { case 5 : std::cout << "It's five\n" ; break ; default : std::cout << "Other\n" ; } return 0 ; }
4. 循环(for/while/do-while)
1 2 3 4 5 6 7 8 9 #include <iostream> int main () { for (int i = 0 ; i < 3 ; ++i) std::cout << "For " << i << "\n" ; int j = 0 ; while (j < 3 ) std::cout << "While " << j++ << "\n" ; int k = 0 ; do { std::cout << "Do-while " << k << "\n" ; } while (++k < 3 ); return 0 ; }
5. 函数定义
1 2 3 4 5 6 7 8 #include <iostream> int add (int a, int b) { return a + b; } int main () { std::cout << add (2 , 3 ) << std::endl; return 0 ; }
6. 数组与字符串
1 2 3 4 5 6 7 8 9 #include <iostream> #include <string> int main () { int arr[3 ] = {1 , 2 , 3 }; std::string s = "Hello" ; for (int i = 0 ; i < 3 ; ++i) std::cout << arr[i] << " " ; std::cout << "\n" << s << std::endl; return 0 ; }
7. 指针和引用
1 2 3 4 5 6 7 8 9 #include <iostream> int main () { int a = 10 ; int * p = &a; int & r = a; *p = 20 ; std::cout << a << " " << r << std::endl; return 0 ; }
8. 类与对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 #include <iostream> class Person {public : std::string name; int age; void greet () { std::cout << "Hi, I'm " << name << std::endl; } }; int main () { Person p{"Alice" , 25 }; p.greet (); return 0 ; }
9. 构造函数和析构函数
1 2 3 4 5 6 7 8 9 10 #include <iostream> class Demo {public : Demo () { std::cout << "Constructor\n" ; } ~Demo () { std::cout << "Destructor\n" ; } }; int main () { Demo d; return 0 ; }
10. 继承与多态
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <iostream> class Base {public : virtual void speak () { std::cout << "Base speaking\n" ; } }; class Derived : public Base {public : void speak () override { std::cout << "Derived speaking\n" ; } }; int main () { Base* obj = new Derived (); obj->speak (); delete obj; return 0 ; }
11. STL 容器(vector 示例)
1 2 3 4 5 6 7 8 #include <iostream> #include <vector> int main () { std::vector<int > v = {1 , 2 , 3 }; v.push_back (4 ); for (int x : v) std::cout << x << " " ; return 0 ; }
12. 异常处理(try-catch)
1 2 3 4 5 6 7 8 9 10 #include <iostream> #include <stdexcept> int main () { try { throw std::runtime_error ("Something went wrong" ); } catch (const std::exception& e) { std::cout << "Caught: " << e.what () << std::endl; } return 0 ; }
13. Lambda 表达式
1 2 3 4 5 6 7 8 9 #include <iostream> #include <vector> #include <algorithm> int main () { std::vector<int > v = {5 , 2 , 8 }; std::sort (v.begin (), v.end (), [](int a, int b) { return a < b; }); for (int x : v) std::cout << x << " " ; return 0 ; }
14. 文件读写(fstream)
1 2 3 4 5 6 7 8 9 10 11 12 13 #include <fstream> #include <iostream> int main () { std::ofstream out ("test.txt" ) ; out << "Hello File" ; out.close (); std::ifstream in ("test.txt" ) ; std::string content; in >> content; std::cout << content << std::endl; return 0 ; }
15. 模板函数与类
1 2 3 4 5 6 7 8 9 10 #include <iostream> template <typename T>T add (T a, T b) { return a + b; } int main () { std::cout << add <int >(3 , 4 ) << "\n" ; std::cout << add <double >(2.5 , 1.5 ) << "\n" ; return 0 ; }
16. 函数默认参数与重载
1 2 3 4 5 6 7 8 9 10 11 12 13 #include <iostream> void greet (std::string name = "Guest" ) { std::cout << "Hello, " << name << "!\n" ; } void greet (int count) { for (int i = 0 ; i < count; ++i) greet (); } int main () { greet (); greet ("Alice" ); greet (2 ); return 0 ; }
17. 命名空间与别名
1 2 3 4 5 6 7 8 9 #include <iostream> namespace math { int add (int a, int b) { return a + b; } } namespace m = math; int main () { std::cout << m::add (1 , 2 ) << std::endl; return 0 ; }
18. 枚举(enum class)
1 2 3 4 5 6 7 #include <iostream> enum class Color { Red, Green, Blue };int main () { Color c = Color::Green; if (c == Color::Green) std::cout << "Green\n" ; return 0 ; }
19.
智能指针(std::unique_ptr
,
std::shared_ptr
)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 #include <iostream> #include <memory> class MyClass {public : MyClass () { std::cout << "Construct\n" ; } ~MyClass () { std::cout << "Destruct\n" ; } }; int main () { std::unique_ptr<MyClass> uPtr = std::make_unique <MyClass>(); std::shared_ptr<MyClass> sPtr1 = std::make_shared <MyClass>(); std::shared_ptr<MyClass> sPtr2 = sPtr1; return 0 ; }
20. 类型推导 (auto
,
decltype
)
1 2 3 4 5 6 7 8 #include <iostream> int add (int a, int b) { return a + b; }int main () { auto x = 42 ; decltype (add (1 ,2 )) y = 5 ; std::cout << x + y << std::endl; return 0 ; }
21. 结构化绑定(C++17)
1 2 3 4 5 6 7 8 9 10 #include <iostream> #include <tuple> std::tuple<int , std::string> getData () { return {1 , "Alice" }; } int main () { auto [id, name] = getData (); std::cout << id << " " << name << "\n" ; return 0 ; }
22. 范围 for 与初始化
if/while(C++17)
1 2 3 4 5 6 7 8 9 10 #include <iostream> #include <vector> int main () { std::vector<int > nums = {1 , 2 , 3 }; for (auto x : nums) std::cout << x << " " ; if (int x = nums[0 ]; x == 1 ) std::cout << "\nFirst is 1\n" ; return 0 ; }
23. constexpr
常量表达式
1 2 3 4 5 6 7 8 9 #include <iostream> constexpr int square (int x) { return x * x; } int main () { constexpr int val = square (5 ); std::cout << val << std::endl; return 0 ; }
24. 可变参数模板(Variadic
Templates)
1 2 3 4 5 6 7 8 9 10 11 12 13 #include <iostream> void print () {}template <typename T, typename ... Args>void print (T first, Args... rest) { std::cout << first << " " ; print (rest...); } int main () { print (1 , "hello" , 3.14 , 'x' ); return 0 ; }
25. 类型特征与
std::enable_if
1 2 3 4 5 6 7 8 9 10 11 12 13 14 #include <iostream> #include <type_traits> template <typename T>typename std::enable_if<std::is_integral<T>::value, T>::type add (T a, T b) { return a + b; } int main () { std::cout << add (2 , 3 ) << std::endl; return 0 ; }
26. Lambda 捕获(值/引用/默认)
1 2 3 4 5 6 7 8 #include <iostream> int main () { int a = 10 , b = 20 ; auto f1 = [a, &b]() { std::cout << a << " " << b << std::endl; }; b = 30 ; f1 (); return 0 ; }
27. std::function
与函数对象
1 2 3 4 5 6 7 8 9 10 #include <iostream> #include <functional> int add (int x, int y) { return x + y; }int main () { std::function<int (int , int )> func = add; std::cout << func (2 , 3 ) << std::endl; return 0 ; }
28. 多线程(std::thread
)
1 2 3 4 5 6 7 8 9 10 11 12 #include <iostream> #include <thread> void sayHello () { std::cout << "Hello from thread\n" ; } int main () { std::thread t (sayHello) ; t.join (); return 0 ; }
29. 锁与互斥(std::mutex
)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #include <iostream> #include <thread> #include <mutex> std::mutex mtx; int counter = 0 ;void increment () { for (int i = 0 ; i < 1000 ; ++i) { std::lock_guard<std::mutex> lock (mtx) ; ++counter; } } int main () { std::thread t1 (increment) , t2 (increment) ; t1. join (); t2. join (); std::cout << "Counter: " << counter << std::endl; return 0 ; }
1 2 3 4 5 6 7 8 9 10 11 #include <iostream> #include <vector> #include <algorithm> int main () { std::vector<int > v = {3 , 1 , 4 }; std::sort (v.begin (), v.end ()); std::transform (v.begin (), v.end (), v.begin (), [](int x) { return x * 2 ; }); for (int x : v) std::cout << x << " " ; return 0 ; }
31.
协程(C++20)co_yield
, co_return
,
co_await
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 #include <iostream> #include <coroutine> struct Generator { struct promise_type ; using handle_type = std::coroutine_handle<promise_type>; struct promise_type { int current_value; auto get_return_object () { return Generator{handle_type::from_promise (*this )}; } auto initial_suspend () { return std::suspend_always{}; } auto final_suspend () noexcept { return std::suspend_always{}; } void return_void () {} void unhandled_exception () { std::exit (1 ); } auto yield_value (int value) { current_value = value; return std::suspend_always{}; } }; handle_type coro; explicit Generator (handle_type h) : coro(h) { } ~Generator () { if (coro) coro.destroy (); } bool next () { coro.resume (); return !coro.done (); } int value () const { return coro.promise ().current_value; } }; Generator counter (int max) { for (int i = 0 ; i <= max; ++i) co_yield i; } int main () { auto gen = counter (5 ); while (gen.next ()) { std::cout << gen.value () << " " ; } return 0 ; }
32. std::optional
(可选值)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 #include <iostream> #include <optional> std::optional<int > divide (int a, int b) { if (b == 0 ) return std::nullopt ; return a / b; } int main () { auto result = divide (10 , 2 ); if (result) std::cout << "Result: " << *result << std::endl; else std::cout << "Divide by zero!" << std::endl; return 0 ; }
33.
std::variant
和 std::visit
(类型安全的
union)
1 2 3 4 5 6 7 8 9 10 11 12 13 #include <iostream> #include <variant> int main () { std::variant<int , std::string> data = 10 ; data = "Hello" ; std::visit ([](auto && val) { std::cout << val << std::endl; }, data); return 0 ; }
34. Concepts(概念约束,C++20)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 #include <iostream> #include <concepts> template <typename T>concept Addable = requires (T a, T b) { a + b; }; template <Addable T>T add (T a, T b) { return a + b; } int main () { std::cout << add (3 , 4 ) << std::endl; return 0 ; }
35. 模板元编程(Type Traits +
递归模板)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include <iostream> #include <type_traits> template <int N>struct Factorial { static constexpr int value = N * Factorial<N - 1 >::value; }; template <>struct Factorial <0 > { static constexpr int value = 1 ; }; int main () { std::cout << Factorial<5 >::value << std::endl; return 0 ; }
36. CRTP(奇异递归模板模式)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 #include <iostream> template <typename Derived>class Base {public : void interface () { static_cast <Derived*>(this )->implementation (); } }; class Derived : public Base<Derived> {public : void implementation () { std::cout << "Derived implementation\n" ; } }; int main () { Derived d; d.interface (); return 0 ; }
37. 泛型 Lambda(C++14+,C++20
支持模板参数)
1 2 3 4 5 6 7 #include <iostream> int main () { auto add = [](auto a, auto b) { return a + b; }; std::cout << add (1 , 2 ) << " " << add (1.5 , 2.5 ) << "\n" ; return 0 ; }
38. 类型擦除:使用
std::function
1 2 3 4 5 6 7 8 9 10 #include <iostream> #include <functional> void sayHi () { std::cout << "Hi\n" ; }int main () { std::function<void ()> f = sayHi; f (); return 0 ; }
39. 自定义迭代器(最简可用版)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #include <iostream> class MyRange {public : struct Iterator { int current; int operator *() const { return current; } Iterator& operator ++() { ++current; return *this ; } bool operator !=(const Iterator& other) const { return current != other.current; } }; Iterator begin () const { return {0 }; } Iterator end () const { return {5 }; } }; int main () { for (int i : MyRange ()) { std::cout << i << " " ; } return 0 ; }
40.
[[nodiscard]]
, [[maybe_unused]]
,
[[deprecated]]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 #include <iostream> [[nodiscard]] int importantValue () { return 42 ; } [[deprecated ("Use newFunction instead" )]] void oldFunction () {} int main () { std::cout << importantValue () << std::endl; [[maybe_unused]] int unused = 123 ; return 0 ; }
41. C++20 模块(Modules)
⚠️ 需编译器支持(如 GCC 11+/Clang 13+/MSVC 2019+),推荐使用 CMake +
MSVC 或 g++ -fmodules-ts
✅ 示例结构:
math.ixx
(模块接口文件)
1 2 3 4 5 export module math;export int add (int a, int b) { return a + b; }
main.cpp
1 2 3 4 5 6 7 import math;#include <iostream> int main () { std::cout << add (2 , 3 ) << "\n" ; return 0 ; }
✅ 编译指令(GCC 示例):
1 2 g++ -std=c++20 -fmodules-ts math.ixx -c -o math.o g++ -std=c++20 -fmodules-ts main.cpp math.o -o main
42.
三向比较(<=>) - C++20 Spaceship Operator
✅ 自动生成所有比较运算符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 #include <iostream> #include <compare> struct Point { int x, y; auto operator <=>(const Point&) const = default ; }; int main () { Point a{1 , 2 }, b{1 , 3 }; std::cout << std::boolalpha << (a < b) << "\n" ; std::cout << (a == b) << "\n" ; return 0 ; }
✅ 自定义三向比较返回值(强/弱/部分顺序)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include <iostream> #include <compare> struct Weird { int x; std::partial_ordering operator <=>(const Weird& other) const { if (x < 0 || other.x < 0 ) return std::partial_ordering::unordered; return x <=> other.x; } }; int main () { Weird a{5 }, b{-1 }; std::cout << std::boolalpha << (a < b) << "\n" ; return 0 ; }
43.
协程完整框架(promise_type 全流程)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 #include <iostream> #include <coroutine> #include <memory> struct Task { struct promise_type { Task get_return_object () { return Task{std::coroutine_handle<promise_type>::from_promise (*this )}; } std::suspend_never initial_suspend () { return {}; } std::suspend_never final_suspend () noexcept { return {}; } void return_void () {} void unhandled_exception () { std::exit (1 ); } }; std::coroutine_handle<promise_type> coro; Task (std::coroutine_handle<promise_type> h) : coro (h) {} ~Task () { if (coro) coro.destroy (); } }; Task sayHello () { std::cout << "Start coroutine\n" ; co_return ; } int main () { sayHello (); return 0 ; }
✅ 补充说明:
promise_type
控制协程生命周期
get_return_object()
返回外部包装类型
可进一步添加 co_await
处理异步等待等(协程通信)
44. C++ GUI 示例(使用
SFML 简洁 GUI)
⚠️ GUI 不在标准库中,推荐使用跨平台库如 SFML
,
Dear ImGui
, Qt
,这里给出 SFML 示例(需安装
SFML)
✅ 示例(创建窗口 + 渲染圆形)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #include <SFML/Graphics.hpp> int main () { sf::RenderWindow window (sf::VideoMode(400 , 300 ), "My GUI" ) ; sf::CircleShape shape (50 ) ; shape.setFillColor (sf::Color::Green); shape.setPosition (100 , 100 ); while (window.isOpen ()) { sf::Event event; while (window.pollEvent (event)) if (event.type == sf::Event::Closed) window.close (); window.clear (); window.draw (shape); window.display (); } return 0 ; }
✅ 编译方式(Linux/macOS)
1 g++ main.cpp -o app -lsfml-graphics -lsfml-window -lsfml-system
🧩 也可以使用 Dear
ImGui 进行现代 GUI 编程,推荐结合 SDL/OpenGL。