這是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)
?遍歷容器元素