
基础语法与结构C 程序通常从main()函数开始执行。一个简单的程序示例#include iostream using namespace std; int main() { cout Hello, World! endl; return 0; }#include iostream引入输入输出流库。using namespace std使用标准命名空间避免重复写std::。cout和endl分别用于输出和换行。变量与数据类型C 是静态类型语言变量需先声明后使用。常见数据类型整型int4字节、short2字节、long8字节。浮点型float4字节、double8字节。字符型char1字节存储单个字符。布尔型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 vectorint nums {1, 2, 3}; nums.push_back(4); // 添加元素 cout nums[2]; // 输出 3映射map键值对集合。#include map mapstring, 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; }