这是5分钟入门 C++ 的精简 Demo,尽量涵盖核心概念:变量、函数、类、控制流、STL 容器,让你快速理解 C++ 的基本用法。
#include <iostream> // 输入输出
#include <vector> // 动态数组
#include <algorithm> // 常用算法// 函数定义
int add(int a, int b) {return a + b;
}// 类和构造函数
class Person {
public:std::string name;int age;Person(const std::string& n, int a) : name(n), age(a) {}void greet() {std::cout << "Hello, my name is " << name << " and I am " << age << " years old.\n";}
};int main() {// 变量和基本类型int x = 5;double y = 3.14;std::string msg = "C++ is fun!";std::cout << msg << "\n";std::cout << "x + y = " << x + y << "\n";// 控制流if (x > 0) {std::cout << "x is positive\n";} else {std::cout << "x is non-positive\n";}// 循环std::cout << "Loop 1 to 5: ";for (int i = 1; i <= 5; ++i) {std::cout << i << " ";}std::cout << "\n";// 使用函数std::cout << "add(10, 20) = " << add(10, 20) << "\n";// 使用类Person p("Alice", 30);p.greet();// STL 容器和算法std::vector<int> nums = {3, 1, 4, 1, 5};std::sort(nums.begin(), nums.end());std::cout << "Sorted nums: ";for (int n : nums) {std::cout << n << " ";}std::cout << "\n";return 0;
}
核心点解析
输入输出:
std::cout << ...
,std::endl
换行。变量和类型:
int
,double
,std::string
。函数:
int add(int a, int b)
,支持参数和返回值。类和对象:
构造函数
Person(const std::string& n, int a)
成员函数
greet()
控制流:
if-else
、for
循环STL 容器:
std::vector
,常用算法std::sort
范围 for 循环:
for (int n : nums)
遍历容器元素