基础语法与结构
C++ 程序通常从main()函数开始执行。一个简单的程序示例:
#include <iostream> using namespace std; int main() { cout << "Hello, World!" << endl; return 0; }#include <iostream>:引入输入输出流库。using namespace std:使用标准命名空间,避免重复写std::。cout和endl:分别用于输出和换行。
变量与数据类型
C++ 是静态类型语言,变量需先声明后使用。常见数据类型:
- 整型:
int(4字节)、short(2字节)、long(8字节)。 - 浮点型:
float(4字节)、double(8字节)。 - 字符型:
char(1字节),存储单个字符。 - 布尔型:
bool,值为true或false。
示例:
int age = 25; double price = 99.99; char grade = 'A'; bool isPassed = true;控制结构
条件语句:
if (age >= 18) { cout << "Adult" << endl; } else { cout << "Minor" << endl; }循环语句:
for循环:
for (int i = 0; i < 5; i++) { cout << i << endl; }while循环:
int i = 0; while (i < 5) { cout << i << endl; i++; }函数
函数用于封装可重复使用的代码块。示例:
int add(int a, int b) { return a + b; } int main() { int result = add(3, 4); cout << result << endl; // 输出 7 return 0; }数组与字符串
数组:存储固定大小的同类型元素。
int numbers[5] = {1, 2, 3, 4, 5}; cout << numbers[0]; // 输出 1字符串:C++ 提供string类(需包含<string>)。
#include <string> string name = "Alice"; cout << name.length(); // 输出 5指针与引用
指针:存储内存地址。
int num = 10; int* ptr = # // ptr 指向 num 的地址 cout << *ptr; // 输出 10(解引用)引用:变量的别名。
int a = 5; int& ref = a; // ref 是 a 的引用 ref = 10; // a 的值变为 10面向对象编程(OOP)
类与对象:
class Person { public: string name; int age; void greet() { cout << "Hello, " << name << endl; } }; int main() { Person p1; p1.name = "Bob"; p1.age = 30; p1.greet(); // 输出 "Hello, Bob" return 0; }构造函数:初始化对象。
class Person { public: Person(string n, int a) { name = n; age = a; } string name; int age; }; Person p1("Alice", 25); // 调用构造函数文件操作
使用<fstream>进行文件读写。
#include <fstream> ofstream outFile("test.txt"); outFile << "Hello, File!" << endl; outFile.close(); ifstream inFile("test.txt"); string line; getline(inFile, line); cout << line; // 输出 "Hello, File!" inFile.close();标准模板库(STL)
向量(vector):动态数组。
#include <vector> vector<int> nums = {1, 2, 3}; nums.push_back(4); // 添加元素 cout << nums[2]; // 输出 3映射(map):键值对集合。
#include <map> map<string, int> ages; ages["Alice"] = 25; cout << ages["Alice"]; // 输出 25异常处理
使用try-catch捕获异常。
try { int x = 10 / 0; // 除零错误 } catch (const exception& e) { cout << "Error: " << e.what() << endl; }