C++基础
C++ 基础语法
C++ 是一种静态类型、编译式、通用的编程语言,支持过程化编程、面向对象编程和泛型编程。以下是一些基础语法和概念。
变量与数据类型
C++ 提供了多种内置数据类型:
int age = 25; // 整型
float price = 19.99f; // 单精度浮点
double pi = 3.14159; // 双精度浮点
char grade = 'A'; // 字符
bool is_active = true; // 布尔型
输入与输出
使用 iostream
库进行基本的输入输出操作:
#include <iostream>
using namespace std;int main() {int num;cout << "Enter a number: "; // 输出cin >> num; // 输入cout << "You entered: " << num;return 0;
}
条件语句
C++ 支持 if
、else if
和 else
条件分支:
int score = 85;
if (score >= 90) {cout << "Grade: A";
} else if (score >= 80) {cout << "Grade: B";
} else {cout << "Grade: C";
}
循环结构
常见的循环包括 for
、while
和 do-while
:
for (int i = 0; i < 5; i++) {cout << i << " ";
}int j = 0;
while (j < 5) {cout << j << " ";j++;
}
函数
函数是代码复用的基本单元,可以接受参数并返回值。
#include <iostream>
using namespace std;int add(int a, int b) {return a + b;
}int main() {int result = add(3, 4);cout << "Result: " << result;return 0;
}
函数重载
C++ 允许同名函数通过参数列表的不同进行重载:
int multiply(int a, int b) {return a * b;
}double multiply(double a, double b) {return a * b;
}
数组与字符串
数组用于存储相同类型的多个元素,字符串可以用字符数组或 string
类表示。
数组
int numbers[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {cout << numbers[i] << " ";
}
字符串
#include <string>
using namespace std;string name = "Alice";
cout << "Name: " << name;
指针与引用
指针存储内存地址,引用是变量的别名。
指针
int num = 10;
int *ptr = # // ptr 指向 num 的地址
cout << *ptr; // 解引用输出 10
引用
int num = 10;
int &ref = num; // ref 是 num 的引用
ref = 20; // 修改 ref 即修改 num
cout << num; // 输出 20
面向对象编程
C++ 支持类和对象,是面向对象编程的核心。
类与对象
#include <iostream>
using namespace std;class Rectangle {
public:int width, height;int area() {return width * height;}
};int main() {Rectangle rect;rect.width = 5;rect.height = 10;cout << "Area: " << rect.area();return 0;
}
构造函数与析构函数
class Person {
public:string name;Person(string n) { // 构造函数name = n;}~Person() { // 析构函数cout << "Destroyed";}
};int main() {Person p("Alice");cout << p.name;return 0;
}
标准模板库(STL)
STL 提供了常用数据结构和算法。
向量(Vector)
#include <vector>
using namespace std;vector<int> nums = {1, 2, 3};
nums.push_back(4); // 添加元素
for (int num : nums) {cout << num << " ";
}
映射(Map)
#include <map>
using namespace std;map<string, int> ages;
ages["Alice"] = 25;
ages["Bob"] = 30;
cout << ages["Alice"];
文件操作
使用 fstream
进行文件读写。
#include <fstream>
#include <iostream>using namespace std;int main() {ofstream outfile("test.txt"); // 写入文件outfile << "Hello, C++!";outfile.close();ifstream infile("test.txt"); // 读取文件string line;getline(infile, line);std::cout << line;infile.close();return 0;
}