编程基础——C++语言基础知识

C++语言基础知识

一、控制台程序的基本结构

C++控制台程序通常从一个简单的"Hello World"示例开始,这有助于初学者理解程序的基本结构和工作方式。

示例代码:

1
2
3
4
5
6
7
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!!!" << endl;
return 0;
}
  • #include <iostream>:这是一个预处理指令,用于包含标准输入输出流库,使得可以使用cout进行输出。
  • using namespace std;:这条语句允许我们直接使用标准命名空间中的名称,如coutendl,而无需在前面加std::
  • int main():定义了主函数,这是每个C++程序的入口点。int表示函数返回一个整数给操作系统。
  • cout << "Hello World!!!" << endl;:使用插入操作符<<向控制台输出文本。endl是一个操纵符,用于插入一个换行符并刷新输出缓冲区。
  • return 0;:表示程序正常结束。

二、输入输出语句

C++使用coutcin进行标准输出和输入。

(1)输出语句cout

  • cout用于向控制台输出文本或变量。
  • endl用于结束当前行并刷新输出缓冲区。

示例:

1
2
3
cout << "Hello world" << endl;
int a = 122;
cout << a << endl;

(2)输入语句cin

  • cin用于从标准输入(通常是键盘)读取数据。

示例:

1
2
3
int a;
char b;
cin >> a >> b;

三、变量和常量

(1)常量

在C++中,常量是一旦初始化后其值不可改变的实体。

1. 整数

使用const关键字定义整数常量:

1
const int maxStudents = 30;

2. 浮点数

定义浮点数常量:

1
const double pi = 3.14159;

(2)变量

变量是可以在程序执行期间改变值的实体。

1. 整型(int

用于存储整数。

1
int age = 25;

2. 浮点型(float, double

用于存储带小数点的数字。

1
double salary = 4589.50;

3. 布尔型(bool

表示逻辑真(true)或假(false)。

1
bool isOnline = true;

4. 字符型(char

用于存储单个字符。

1
char grade = 'A';

5. 字符串类型(string

用于存储一系列字符。

1
string name = "Alice";

四、基本程序结构

(1)顺序结构

顺序结构是最基本的程序结构,程序按照代码的书写顺序从上到下执行指令。在C++中,每条指令通常以分号(;)结束,表示一条语句的结束。这种结构适用于所有基本操作,如变量声明、赋值、调用函数等。

示例:

1
2
3
4
5
6
int main() {
int a = 5; // 声明并初始化变量
a = a + 3; // 修改变量的值
cout << a << endl; // 输出变量的值
return 0; // 返回操作系统0,表示程序正常结束
}

(2)选择结构

选择结构允许程序基于条件判断来选择不同的执行路径。C++提供了多种选择结构,包括if语句、else语句、else if语句以及switch语句。

1. if语句

用于基于条件执行代码块。如果条件为真(true),则执行if块内的代码。

示例:
1
2
3
if (a > 0) {
cout << "a is positive." << endl;
}

2. elseelse if语句

else用于当if条件为假(false)时执行的代码块。else if允许对多个条件进行检查。

示例:
1
2
3
4
5
6
7
if (a > 0) {
cout << "a is positive." << endl;
} else if (a < 0) {
cout << "a is negative." << endl;
} else {
cout << "a is zero." << endl;
}

3. switch语句

用于基于变量的值执行多个代码块中的一个。每个代码块由case标签指定,并且通常在末尾使用break来防止执行流跳转到下一个case

示例:
1
2
3
4
5
6
7
8
9
10
switch (a) {
case 1:
cout << "One" << endl;
break;
case 2:
cout << "Two" << endl;
break;
default:
cout << "Other" << endl;
}

(3)循环结构

循环结构允许重复执行代码块直到满足特定条件。C++中主要的循环结构有for循环、while循环和do-while循环。

1. for循环

用于在已知循环次数的情况下重复执行代码块。它包括初始化表达式、循环条件和迭代表达式。

示例:
1
2
3
for (int i = 0; i < 5; i++) {
cout << i << " ";
}

2. while循环

在循环开始前检查条件,只有条件为真时才执行循环体。

示例:
1
2
3
4
5
int i = 0;
while (i < 5) {
cout << i << " ";
i++;
}

3. do-while循环

至少执行一次循环体,因为条件检查在循环体之后进行。

示例:
1
2
3
4
5
int i = 0;
do {
cout << i << " ";
i++;
} while (i < 5);

五、高级数据类型

(1)整型

  • int: 用于存储整数。占用通常是4个字节(但这依赖于编译器和计算机架构)。
  • short: 用于存储较小的整数,通常是2个字节。
  • long: 用于存储较大的整数,通常是至少4个字节。
  • long long: 用于存储非常大的整数,通常是8个字节。

(2)浮点型

  • float: 单精度浮点数。用于存储有小数部分的数字,精度约为7位十进制数字。
  • double: 双精度浮点数。用于存储大和/或非常精确的浮点数,精度约为15位十进制数字。
  • long double: 扩展精度浮点数,精度和大小依赖于编译器和计算机架构。

(3)字符型

  • char: 用于存储单个字符,如'a''1'。占用1个字节。
  • wchar_t: 用于存储宽字符,通常用于Unicode字符,大小可能是2或4个字节。

(4)布尔型

  • bool: 用于表示逻辑值truefalse

(5)其他类型

  • void: 表示无类型,通常用于指定不返回值的函数的返回类型。
  • auto: 自动类型推断,允许编译器根据初始化表达式推断变量的类型。

(6)复合数据类型

1. 数组

  • 用于存储同类型元素的固定大小序列。
  • 示例:int numbers[10]; // 声明一个整型数组,包含10个整数。

2. 结构体

  • 允许将不同的数据类型组合成一个单一实体。
  • 示例:
    1
    2
    3
    4
    struct Person {
    string name;
    int age;
    };

3. 联合

  • 允许在相同的内存位置存储不同的数据类型,但一次只能使用一个。
  • 示例:
    1
    2
    3
    4
    5
    union Data {
    int i;
    float f;
    char str[20];
    };

4. 枚举

  • 定义一个变量,它可以持有一组整型常数中的任意一个。
  • 示例:
    1
    enum Color { red, green, blue };

(7)指针

  • 存储变量地址的变量,可用于间接访问内存。
  • 示例:int* ptr = &variable; // ptr现在指向variable的地址。

(8)动态数据结构

  • 动态数组(向量):使用std::vector可以动态地增减大小。
  • 链表:手动或使用std::list进行管理,允许元素的动态插入和删除。

(9)类

  • 用户定义的数据类型,允许封装数据和相关操作。
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    class Car {
    private:
    string brand;
    int year;
    public:
    void drive();
    void stop();
    };

六、函数

(1)函数的定义和声明

函数是执行特定任务的一组语句的集合。函数通常包括返回类型、函数名、参数列表和函数体。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

// 函数声明
int add(int a, int b);

int main() {
int result = add(5, 3);
cout << "Sum: " << result << endl;
return 0;
}

// 函数定义
int add(int a, int b) {
return a + b;
}

(2)函数的参数传递

1. 值传递

参数的值传递给函数,不影响原变量。

2. 引用传递

传递参数的引用,函数内修改会影响原变量。

示例:
1
2
3
4
5
void swap(int &x, int &y) {
int temp = x;
x = y;
y = temp;
}

(3)函数的返回值

函数可以返回一个值,可以是基本数据类型、指针、引用或用户定义的类型。

七、面向对象编程(OOP)

(1)类和对象

类是用户定义的类型,用于封装数据和操作。对象是类的实例。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Car {
public:
string brand;
int year;

void drive() {
cout << "Driving" << endl;
}
};

int main() {
Car myCar;
myCar.brand = "Toyota";
myCar.year = 2020;
myCar.drive();
return 0;
}

(2)构造函数和析构函数

构造函数在创建对象时初始化对象,析构函数在对象销毁时清理资源。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Car {
public:
string brand;
int year;

// 构造函数
Car(string b, int y) {
brand = b;
year = y;
}

// 析构函数
~Car() {
cout << "Car destroyed" << endl;
}
};

int main() {
Car myCar("Toyota", 2020);
myCar.drive();
return 0;
}

(3)继承

继承允许一个类从另一个类继承属性和方法,促进代码重用。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Vehicle {
public:
string brand;
void honk() {
cout << "Honk!" << endl;
}
};

class Car : public Vehicle {
public:
int year;
};

int main() {
Car myCar;
myCar.brand = "Toyota";
myCar.year = 2020;
myCar.honk();
return 0;
}

(4)多态性

多态性允许不同类的对象通过相同的接口调用各自的方法。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Animal {
public:
virtual void sound() {
cout << "Some sound" << endl;
}
};

class Dog : public Animal {
public:
void sound() override {
cout << "Bark" << endl;
}
};

int main() {
Animal *a = new Dog();
a->sound(); // 输出 "Bark"
delete a;
return 0;
}

八、标准模板库(STL)

STL提供了丰富的数据结构和算法。

(1)容器

1. 向量(vector)

动态数组,支持随机访问。

1
2
3
4
5
6
7
8
9
10
#include <vector>
#include <iostream>
using namespace std;

int main() {
vector<int> nums = {1, 2, 3, 4, 5};
nums.push_back(6);
cout << nums[0] << endl;
return 0;
}

2. 列表(list)

双向链表,支持快速插入和删除。

1
2
3
4
5
6
7
8
9
10
#include <list>
#include <iostream>
using namespace std;

int main() {
list<int> nums = {1, 2, 3, 4, 5};
nums.push_back(6);
cout << nums.front() << endl;
return 0;
}

(2)迭代器

迭代器用于遍历容器中的元素。

1
2
3
4
5
6
7
8
9
10
11
12
#include <vector>
#include <iostream>
using namespace std;

int main() {
vector<int> nums = {1, 2, 3, 4, 5};
for (vector<int>::iterator it = nums.begin(); it != nums.end(); ++it) {
cout << *it << " ";
}
cout << endl;
return 0;
}

(3)算法

STL提供了多种算法,如排序、查找、复制等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;

int main() {
vector<int> nums = {5, 2, 9, 1, 5, 6};
sort(nums.begin(), nums.end());
for (int num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}

九、异常处理

异常处理用于捕获和处理运行时错误,增强程序的鲁棒性。

(1)try-catch块

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main() {
try {
int a = 10;
int b = 0;
if (b == 0) {
throw "Division by zero!";
}
int c = a / b;
} catch (const char* msg) {
cerr << "Error: " << msg << endl;
}
return 0;
}

(2)自定义异常类

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <exception>
using namespace std;

class MyException : public exception {
public:
const char* what() const throw() {
return "My custom exception";
}
};

int main() {
try {
throw MyException();
} catch (MyException& e) {
cout << e.what() << endl;
}
return 0;
}

十、文件操作

文件操作允许程序读取和写入文件。

(1)文件的读取

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <fstream>
using namespace std;

int main() {
ifstream infile("example.txt");
if (infile.is_open()) {
string line;
while (getline(infile, line)) {
cout << line << endl;
}
infile.close();
}
return 0;
}

(2)文件的写入

示例:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <fstream>
using namespace std;

int main() {
ofstream outfile("example.txt");
if (outfile.is_open()) {
outfile << "Hello, World!" << endl;
outfile.close();
}
return 0;
}

十一、多线程编程

C++11引入了多线程支持,允许程序并行执行。

(1)创建线程

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <thread>
using namespace std;

void threadFunction() {
cout << "Thread is running" << endl;
}

int main() {
thread t(threadFunction);
t.join();
return 0;
}

(2)线程同步

互斥锁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;

mutex mtx;

void printThread(int n) {
mtx.lock();
cout << "Thread " << n << " is running" << endl;
mtx.unlock();
}

int main() {
thread t1(printThread, 1);
thread t2(printThread, 2);
t1.join();
t2.join();
return 0;
}

十二、C++11及更高版本的新特性

(1)auto关键字

自动类型推断。

1
2
auto x = 10; // int
auto y = 3.14; // double

(2)Lambda表达式

匿名函数。

1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;

int main() {
auto add = [](int a, int b) -> int {
return a + b;
};
cout << add(5, 3) << endl;
return 0;
}

(3)智能指针

管理动态内存。

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <memory>
using namespace std;

int main() {
unique_ptr<int> p1(new int(10));
cout << *p1 << endl;
return 0;
}

(4)范围for循环

遍历容器。

1
2
3
4
5
6
7
8
9
10
11
12
#include <vector>
#include <iostream>
using namespace std;

int main() {
vector<int> nums = {1, 2, 3, 4, 5};
for (int num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}

(5)nullptr关键字

替代NULL

1
int* p = nullptr;

(6)线程支持库

多线程编程。

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <thread>
using namespace std;

void threadFunction() {
cout << "Thread is running" << endl;
}

int main() {
thread t(threadFunction);
t.join();
return 0;
}

编程基础——C++语言基础知识
https://blog.cxhap.top/2024/07/28/编程基础——C-语言基础知识/
作者
DingWH03
发布于
2024年7月28日
许可协议