C++ 基本常识
1. 基础语法结构
1.1 Hello World 示例
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}1.2 基本组成部分
#include:头文件包含using namespace std:使用标准命名空间main():程序入口函数cout:标准输出流endl:换行并刷新缓冲区
2. 数据类型
| 类型 | 说明 | 示例 |
|---|---|---|
int | 整型 | int a = 10; |
float | 单精度浮点型 | float b=3.14; |
double | 双精度浮点型 | double c=3.14; |
char | 字符型 | char d='A'; |
bool | 布尔型 | bool e=true; |
void | 无类型 | 用于函数返回值 |
3. 控制结构
3.1 条件语句
if (condition) {
// 代码
} else if (condition2) {
// 代码
} else {
// 代码
}3.2 循环语句
// for循环
for (int i = 0; i < 10; i++) {
// 代码
}
// while循环
while (condition) {
// 代码
}
// do-while循环
do {
// 代码
} while (condition);4. 函数
4.1 函数定义
返回类型 函数名(参数列表) {
// 函数体
return 返回值; // 非void类型必须
}4.2 函数示例
int add(int a, int b) {
return a + b;
}5. 类和对象
5.1 类定义
class MyClass {
public: // 访问修饰符
// 成员变量
int x;
// 成员函数
void print() {
cout << x << endl;
}
};5.2 对象创建与使用
MyClass obj;
obj.x = 10;
obj.print();6. 指针基础
int var = 20;
int *ptr = &var; // 指针声明和赋值
cout << *ptr; // 解引用输出207. 常用头文件
<iostream>:输入输出流<vector>:动态数组<string>:字符串处理<algorithm>:常用算法<cmath>:数学函数
8. 命名规范建议
- 变量:小驼峰
myVariable - 函数:小驼峰
myFunction() - 类:大驼峰
MyClass - 常量:全大写
MAX_SIZE
9. 编译与执行
g++ program.cpp -o program # 编译
./program # 执行注意:C++是区分大小写的语言,每行语句以分号
;结束