#创作计划# C++基础入门知识梳理
2025-07-31 22:04:53
发布于:浙江
一、C++语言概述
- 高效性:接近底层硬件,执行效率高
- 面向对象:支持封装、继承和多态
- 泛型编程:通过模板实现
- 丰富的标准库:包括容器、算法、字符串处理等
- 兼容C语言:几乎完全兼容C语言的语法和特性
二、基础语法结构
1. 基本程序结构
#include <iostream> // 头文件包含
using namespace std; // 使用标准命名空间
int main() { // 主函数入口
cout << "Hello, World!" << endl; // 输出语句
return 0; // 返回值
}
2. 数据类型
C++中的基本数据类型包括:
类型 | 描述 | 大小(字节) |
---|---|---|
int | 整型 | 4 |
float | 单精度浮点型 | 4 |
double | 双精度浮点型 | 8 |
char | 字符型 | 1 |
bool | 布尔型(true/false) | 1 |
3. 变量与常量
变量声明与初始化:
int a = 10; // 声明并初始化
float b(3.14); // 构造函数式初始化
char c{'A'}; // 列表初始化
常量定义:
const int MAX = 100; // 常量
#define PI 3.14159 // 宏定义
三、运算符与表达式
1. 算术运算符
+ - * / % ++ --
2. 关系运算符
== != > < >= <=
3. 逻辑运算符
&& || !
4. 位运算符
& | ^ ~ << >>
5. 赋值运算符
= += -= *= /= %= &= |= ^= <<= >>=
四、流程控制
1. 条件语句
if-else语句:
if (condition) {
// 代码块
} else if (condition) {
// 代码块
} else {
// 代码块
}
switch语句:
switch(expression) {
case constant1:
// 代码块
break;
case constant2:
// 代码块
break;
default:
// 代码块
}
2. 循环结构
for循环:
for (init; condition; increment) {
// 代码块
}
while循环:
while (condition) {
// 代码块
}
do-while循环:
do {
// 代码块
} while (condition);
五、函数
1. 函数定义
返回类型 函数名(参数列表) {
// 函数体
return 返回值;
}
示例:
int add(int a, int b) {
return a + b;
}
2. 函数参数传递方式
- 值传递
- 指针传递
- 引用传递
3. 函数重载
void print(int i) { cout << i; }
void print(double f) { cout << f; }
void print(string s) { cout << s; }
六、数组与字符串
1. 数组
int arr[5] = {1, 2, 3, 4, 5}; // 一维数组
int matrix[2][3] = {{1,2,3}, {4,5,6}}; // 二维数组
2. 字符串
C风格字符串:
char str[] = "Hello";
C++ string类:
#include <string>
string s = "Hello";
七、指针与引用
1. 指针
int var = 20;
int *ptr = &var; // 指针声明与初始化
cout << *ptr; // 解引用
2. 引用
int var = 10;
int &ref = var; // 引用声明
ref = 20; // 修改引用即修改原变量
八、面向对象基础
1. 类与对象
class Student {
private:
string name;
int age;
public:
void setName(string n) { name = n; }
string getName() { return name; }
};
Student stu;
stu.setName("Alice");
2. 构造函数与析构函数
class MyClass {
public:
MyClass() { cout << "Constructor called"; } // 构造函数
~MyClass() { cout << "Destructor called"; } // 析构函数
};
3. 继承
class Animal {
public:
void eat() { cout << "Eating"; }
};
class Dog : public Animal {
public:
void bark() { cout << "Barking"; }
};
九、标准模板库(STL)简介
1. 容器
vector<int> v = {1, 2, 3}; // 动态数组
list<string> l; // 双向链表
map<string, int> m; // 键值对集合
2. 算法
#include <algorithm>
vector<int> v = {3, 1, 4};
sort(v.begin(), v.end()); // 排序
3. 迭代器
for (auto it = v.begin(); it != v.end(); ++it) {
cout << *it << " ";
}
十、文件操作
1. 写入文件
#include <fstream>
ofstream out("file.txt");
out << "Hello, File!";
out.close();
2. 读取文件
ifstream in("file.txt");
string line;
while (getline(in, line)) {
cout << line << endl;
}
in.close();
全部评论 4
555,语法都学不会
昨天 来自 浙江
0是不是写错了,变量不支持
void
类,只有函数可以昨天 来自 浙江
0好的
昨天 来自 浙江
0
主播主播,我承认你的
ifstream ofstream
确实很厉害,还是太吃操作,有没有什么简单又使用的freopen
推荐一下昨天 来自 浙江
0后面写
昨天 来自 浙江
0昨天 来自 浙江
0
d
昨天 来自 浙江
0
有帮助,赞一个