C++ 是一种强大的多范式编程语言,支持面向对象编程(OOP)、泛型编程(Generic Programming)以及过程式编程。它扩展了 C 语言,并引入了许多高级特性,如类、模板、标准库等。以下是 C++ 的基础语法要点:
每个 C++ 程序都包含一个 main()
函数,这是程序的入口点。
cpp#include <iostream> // 包含输入输出流库
int main() {
std::cout << "Hello, World!" << std::endl; // 输出到控制台
return 0;
}
#include <iostream>
:包含标准输入输出库。std::cout
:用于输出数据。std::endl
:换行符。C++ 支持多种基本数据类型:
int
, short
, long
, long long
float
, double
, long double
char
, wchar_t
bool
cppint age = 25;
float height = 5.7f;
char initial = 'J';
bool isStudent = true;
使用 std::cin
和 std::cout
进行输入和输出。
cpp#include <iostream>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number; // 接收用户输入
std::cout << "You entered: " << number << std::endl;
return 0;
}
cppif (condition) {
// 当条件为真时执行
} else if (anotherCondition) {
// 其他条件
} else {
// 默认情况
}
for
循环:cppfor (int i = 0; i < 5; i++) {
std::cout << i << std::endl;
}
while
循环:cppint j = 0;
while (j < 5) {
std::cout << j << std::endl;
j++;
}
do...while
循环:cppint k = 0;
do {
std::cout << k << std::endl;
k++;
} while (k < 5);
函数用于封装代码块以实现特定功能。
cpp#include <iostream>
int add(int a, int b) { // 定义函数
return a + b;
}
int main() {
int result = add(5, 3); // 调用函数
std::cout << "Result: " << result << std::endl;
return 0;
}
数组是一系列相同类型的元素集合。
cppint numbers[5] = {1, 2, 3, 4, 5};
std::cout << numbers[0] << std::endl; // 输出第一个元素
指针存储变量的内存地址。
cppint var = 20;
int* ptr = &var; // ptr 指向 var 的地址
std::cout << "Value of var: " << *ptr << std::endl; // 使用 * 访问值
引用是变量的别名,提供更简洁的方式操作变量。
cppint x = 10;
int& ref = x; // ref 是 x 的引用
ref = 20; // 修改 ref 会同时修改 x
std::cout << "x: " << x << std::endl; // 输出: x: 20
C++ 中的核心概念是类和对象。类定义了一种新的数据类型,而对象是类的实例。
cpp#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
void introduce() {
cout << "My name is " << name << " and I am " << age << " years old." << endl;
}
};
int main() {
Person person1;
person1.name = "Alice";
person1.age = 30;
person1.introduce(); // 输出: My name is Alice and I am 30 years old.
return 0;
}
构造函数在创建对象时调用,析构函数在对象销毁时调用。
cppclass MyClass {
public:
MyClass() {
cout << "Constructor called!" << endl;
}
~MyClass() {
cout << "Destructor called!" << endl;
}
};
int main() {
MyClass obj; // 创建对象时自动调用构造函数
return 0; // 程序结束时自动调用析构函数
}
C++ 支持继承,允许一个类从另一个类派生。
cppclass Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};
class Dog : public Animal { // Dog 继承自 Animal
public:
void bark() {
cout << "Barking..." << endl;
}
};
int main() {
Dog dog;
dog.eat(); // 继承自 Animal
dog.bark(); // Dog 自己的方法
return 0;
}
通过虚函数实现运行时多态。
cpp#include <iostream>
using namespace std;
class Animal {
public:
virtual void speak() { // 虚函数
cout << "Animal speaks" << endl;
}
};
class Dog : public Animal {
public:
void speak() override { // 重写虚函数
cout << "Dog barks" << endl;
}
};
int main() {
Animal* animal = new Dog();
animal->speak(); // 输出: Dog barks
delete animal;
return 0;
}
C++ 提供了丰富的标准库,包括容器、算法和迭代器。
vector
:动态数组。cpp#include <vector>
#include <iostream>
int main() {
vector<int> nums = {1, 2, 3};
nums.push_back(4); // 添加元素
for (int num : nums) {
cout << num << " "; // 输出: 1 2 3 4
}
return 0;
}
map
:键值对容器。cpp#include <map>
#include <iostream>
int main() {
map<string, int> scores;
scores["Alice"] = 90;
scores["Bob"] = 85;
cout << "Alice's score: " << scores["Alice"] << endl; // 输出: 90
return 0;
}
sort
:排序。cpp#include <algorithm>
#include <vector>
#include <iostream>
int main() {
vector<int> nums = {3, 1, 4, 2};
sort(nums.begin(), nums.end());
for (int num : nums) {
cout << num << " "; // 输出: 1 2 3 4
}
return 0;
}
C++ 提供了文件流(fstream
)来处理文件读写。
cpp#include <fstream>
#include <iostream>
int main() {
ofstream file("example.txt");
if (file.is_open()) {
file << "Hello, File!" << endl;
file.close();
}
ifstream inputFile("example.txt");
string line;
if (inputFile.is_open()) {
while (getline(inputFile, line)) {
cout << line << endl; // 输出文件内容
}
inputFile.close();
}
return 0;
}
C++ 支持异常处理机制,用于捕获和处理运行时错误。
cpp#include <iostream>
using namespace std;
int main() {
try {
throw runtime_error("An error occurred!");
} catch (const exception& e) {
cout << "Caught exception: " << e.what() << endl;
}
return 0;
}
C++ 模板允许编写与类型无关的代码,支持泛型编程。模板可以是函数模板或类模板。
cpptemplate<typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
int main() {
cout << "Max of 3 and 4: " << max<int>(3, 4) << endl;
cout << "Max of 3.5 and 2.5: " << max<double>(3.5, 2.5) << endl;
return 0;
}
cpptemplate<typename T>
class Pair {
public:
T first, second;
Pair(T a, T b) : first(a), second(b) {}
};
int main() {
Pair<int> p1(6, 9);
cout << "Pair values: " << p1.first << ", " << p1.second << endl;
return 0;
}
除了前面提到的基本容器和算法,STL 还包括许多其他有用的组件。
迭代器提供了一种统一的方式来遍历不同的容器。
cpp#include <vector>
#include <iostream>
int main() {
std::vector<int> vec = {1, 2, 3, 4};
for (std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << " "; // 输出: 1 2 3 4
}
return 0;
}
使用范围 for
循环简化:
cppfor (auto& elem : vec) {
std::cout << elem << " ";
}
更多的 STL 算法,如 find
, count_if
, transform
等。
cpp#include <algorithm>
#include <vector>
#include <iostream>
bool is_odd(int i) {
return i % 2 != 0;
}
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
int odd_count = std::count_if(numbers.begin(), numbers.end(), is_odd);
std::cout << "Number of odd elements: " << odd_count << std::endl;
return 0;
}
Lambda 表达式提供了一种简洁的方式定义匿名函数对象。
cpp#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5};
std::sort(nums.begin(), nums.end(), [](int a, int b) {
return a > b; // 降序排序
});
for (auto num : nums) {
std::cout << num << " "; // 输出: 5 4 3 2 1
}
return 0;
}
智能指针帮助自动管理动态分配内存,避免内存泄漏。
unique_ptr
:独占所有权。cpp#include <memory>
#include <iostream>
int main() {
std::unique_ptr<int> ptr(new int(10));
std::cout << *ptr << std::endl; // 输出: 10
return 0;
}
shared_ptr
:共享所有权。cpp#include <memory>
#include <iostream>
int main() {
std::shared_ptr<int> ptr1 = std::make_shared<int>(20);
std::shared_ptr<int> ptr2 = ptr1;
std::cout << "Ptr1 use count: " << ptr1.use_count() << std::endl; // 输出: 2
return 0;
}
weak_ptr
:用于解决循环引用问题。cpp#include <memory>
#include <iostream>
class B;
class A {
std::weak_ptr<B> b_ptr;
public:
void setB(std::shared_ptr<B> ptr) { b_ptr = ptr; }
void showB() {
if (auto sp = b_ptr.lock()) {
std::cout << "B is alive" << std::endl;
} else {
std::cout << "B is dead" << std::endl;
}
}
};
class B {
std::shared_ptr<A> a_ptr;
public:
void setA(std::shared_ptr<A> ptr) { a_ptr = ptr; }
};
int main() {
auto a = std::make_shared<A>();
auto b = std::make_shared<B>();
a->setB(b);
b->setA(a);
return 0;
}
C++11 引入了多线程支持,使并行编程更加容易。
cpp#include <thread>
#include <iostream>
void print_id(int id) {
std::cout << "Thread ID: " << id << std::endl;
}
int main() {
std::thread t1(print_id, 1);
std::thread t2(print_id, 2);
t1.join(); // 等待线程完成
t2.join();
return 0;
}
手动内存管理在 C++ 中仍然很重要,尤其是对于性能要求高的应用。
new
和 delete
动态分配和释放内存。cppint* arr = new int[5]{1, 2, 3, 4, 5};
delete[] arr; // 不要忘记释放内存
预处理器指令在编译前处理代码,主要用于条件编译、文件包含等。
cpp#define DEBUG
#ifdef DEBUG
std::cout << "Debug mode is on" << std::endl;
#endif
cpp#ifndef MYHEADER_H
#define MYHEADER_H
// Header file content
#endif
这些内容涵盖了从模板编程到多线程编程等多个方面的基础知识。