- C++ 基础
- C++ 首页
- C++ 概述
- C++ 环境设置
- C++ 基本语法
- C++ 注释
- C++ Hello World
- C++ 省略命名空间
- C++ 常量/字面量
- C++ 关键字
- C++ 标识符
- C++ 数据类型
- C++ 数值数据类型
- C++ 字符数据类型
- C++ 布尔数据类型
- C++ 变量类型
- C++ 变量作用域
- C++ 多个变量
- C++ 基本输入/输出
- C++ 修饰符类型
- C++ 存储类
- C++ 运算符
- C++ 数字
- C++ 枚举
- C++ 引用
- C++ 日期和时间
- C++ 控制语句
- C++ 决策
- C++ if 语句
- C++ if else 语句
- C++ 嵌套 if 语句
- C++ switch 语句
- C++ 嵌套 switch 语句
- C++ 循环类型
- C++ while 循环
- C++ for 循环
- C++ do while 循环
- C++ foreach 循环
- C++ 嵌套循环
- C++ break 语句
- C++ continue 语句
- C++ goto 语句
- C++ 构造函数
- C++ 构造函数和析构函数
- C++ 复制构造函数
C++ - 速查表
这份C++编程速查表非常方便使用,并在短时间内提供关键信息。它专为希望解决重要主题并深入了解C++编程世界的人们量身定制。这包括人们可能需要浏览的所有主要和次要细节,并包含示例和代码片段,指导人们如何实际使用这种语言。
C++第一个程序 - Hello World
任何编程语言的基础都是其开发过程。任何初学者都是通过学习其语法来开始学习编程语言的。因此,让我们从编写C++中的第一个程序开始,即Hello World -
示例
#include <bits/stdc++.h> using namespace std; // main() is where program execution begins. int main() { cout<<"Hello World"<<endl; // This is where you write your code return 0; }
输出
Hello World
C++ 注释
C++中的注释用于编写对程序员有用的额外信息。C支持单行注释 // 用于指示单行注释,而/* 用于开始多行注释,*/ 用于结束多行注释。
示例
#include <bits/stdc++.h> using namespace std; int main() { /* This is multi-lined comment. The below statement will only print Hello World*/ cout<<"Hello World"<<endl; // This is a single-lined comment return 0; }
输出
Hello World
C++ 输入和输出语句
这里,“cin”是输入语句,后面跟着“>>”,而“cout”是输出语句,后面跟着“>>”。
另请参阅: C++ 基本输入/输出
示例
#include <bits/stdc++.h> using namespace std; int main() { //declaration of an integer variable int age; cout << "Enter your age: "<<endl; cin >> age; cout << "Your age is: " << age << endl; return 0; }
C++ 变量
变量是存储区域,其中可以存储不同类型的数据。c++中的变量必须在使用前声明,并且变量的名称必须以字母开头,并且可以包含字母、数字和下划线(_)。
示例
#include <bits/stdc++.h> using namespace std; int main() { // Declaring multiple variables int a, b, c; char ch; string s; return 0; }
C++ 关键字
关键字是特定语言的编译器保留的特殊类型的单词,程序员不能显式使用它们。其中一些关键字如下 -
asm | else | new | this |
auto | enum | operator | throw |
bool | explicit | private | true |
break | export | protected | try |
case | extern | public | typedef |
catch | false | register | typeid |
char | float | reinterpret_cast | typename |
class | for | return | union |
const | friend | short | unsigned |
const_cast | goto | signed | using |
continue | if | sizeof | virtual |
default | inline | static | void |
delete | int | static_cast | volatile |
do | long | struct | wchar_t |
double | mutable | switch | while |
dynamic_cast | namespace | template |
C++ 数据类型
数据类型是在内存中存储变量的可用存储分类的类型。数据类型可以分为三个部分 -
1. 基本数据类型
基本数据类型已存在于c++语言库中。这些无需任何修改即可使用。
1.1. Int
用于整数数据类型的关键字是 int。整数通常需要 4 个字节的内存空间,范围从 -2147483648 到 2147483647。
1.2. Float
浮点数数据类型用于存储单精度浮点值或十进制值。用于浮点数数据类型的关键字是 float。浮点变量通常需要 4 个字节的内存空间。
1.3. Char
字符数据类型用于存储字符。用于字符数据类型的关键字是 char。字符通常需要 1 个字节的内存空间,范围从 -128 到 127 或 0 到 255。
1.4. Double
双精度浮点数数据类型用于存储双精度浮点值或十进制值。用于双精度浮点数数据类型的关键字是 double。
1.5. String
字符串数据类型用于将多个字符一起存储在一个变量中。
1.6. Bool
布尔数据类型用于存储布尔值或逻辑值。布尔变量可以存储 true 或 false。用于布尔数据类型的关键字是 bool。
示例
int main() { int age=12; //takes only whole numbers, size is 4 Bytes float weight=70.4; //takes decimal valued numbers, size is 4 Bytes char alpha='a'; //takes single characters as per ASCII, size is 1 Bytes string s="hey siri"; //takes multiple characters, size is variable double d=2.2222; //takes more precise floating point numbers, size is 8 Bytes bool k=true; //takes only true or false values (or 0/1) return 0; }
2. 派生数据类型
这些派生自基本数据类型,称为派生数据类型。这些可以有四种类型,即 -
这些将在后面的章节中简要讨论。
3. 用户定义数据类型
这些数据类型由用户自己定义,可以根据用户的意愿进行自定义。这些主要有五种类型 -
3.1. 类
类和对象的概念在本文档的 OOPS 部分进行了说明。可以参考此处的示例。
示例
#include <bits/stdc++.h> using namespace std; class MyClass { public: int myNum; string myString; }; int main() { MyClass myObj; myObj.myNum = 1234567; myObj.myString = "Helloooo"; cout << myObj.myNum << "\n"; cout << myObj.myString; return 0; }
输出
1234567 Helloooo
3.2. 结构体
定义结构体的语法如下。
struct structName{ char varName[size]; int varName; };
3.3. 联合体
定义联合体的语法如下。
Union_Name{ // Declaration of data members }; union_variables;
3.4. 枚举
定义枚举变量的语法如下。
enum nameOfEnum { varName1 = 1, varName2 = 0 };
3.5. Typedef
定义 typedef 的语法如下。
typedef typeName;
示例
#include <bits/stdc++.h> using namespace std; typedef unsigned char BYTE; int main() { BYTE b1, b2; b1 = 'c'; cout << " " << b1; return 0; }
输出
c
C++ 条件语句
条件语句控制程序的流程,当我们需要定义不同的情况和条件时可以使用。原语“if”、“else”、“else if”、“switch”和三元运算符在这种情况下使用。
- if 语句
- if-else 语句
- if-else-if 语句
- 嵌套 if-else 语句
- Switch 语句
- 三元运算符
1. If 语句
当且仅当给定条件为真时,if 语句才执行代码块。
2. if-else 语句
如果 if 语句内的条件为真,则 if 块内的代码将被执行,否则 else 块内的代码将被执行。
3. if-else-if 语句
else if 语句允许您按顺序检查多个条件。
4. 嵌套 if 语句
多个 if 语句可以相互嵌套,以根据需要形成不同的情况。
5. 三元运算符
它充当条件语句,它接受条件语句并返回第一个语句或第二个语句。
6. Switch Case
在有多个条件的情况下,我们可以简单地使用 switch case 语句来更轻松地处理这些条件。
示例
#include <iostream> using namespace std; int main() { //program to explain if, else if and else conditions int age=12; if(age<12) cout<<"YES"<<endl; else if(age>24) cout<<"NO"<<endl; else cout<<"MAYBE"<<endl; //program to explain ternary operator bool x=true; x==1 ? cout<<"true"<<endl : cout<<"false"<<endl; //program to explain switch case with break and default switch (x & x){ case 0 : cout<<"false"<<endl; break; case 1 : cout<<"true"<<endl; break; default: cout<<"invalid"<<endl; break; } return 0; }
输出
MAYBE true true
C++ 运算符
C++ 中的运算符 可以分为 6 种类型 -
1. 算术运算符
这些运算符用于对操作数执行算术或数学运算。例如,‘+’ 用于加法,‘-’ 用于减法,‘*’ 用于乘法等。
示例
#include <iostream> using namespace std; int main() { int a = 8, b = 3; // Addition operator cout << "a + b = " << (a + b) << endl; // Subtraction operator cout << "a - b = " << (a - b) << endl; // Multiplication operator cout << "a * b = " << (a * b) << endl; // Division operator cout << "a / b = " << (a / b) << endl; // Modulo operator cout << "a % b = " << (a % b) << endl; //unary operators a++; cout<<a<<endl; a--; cout<<a<<endl; int k=++a + ++b; cout<<k<<endl; k=++a - --b; cout<<k<<endl; return 0; }
输出
a + b = 11 a - b = 5 a * b = 24 a / b = 2 a % b = 2 9 8 13 7
2. 关系运算符
这些运算符用于比较两个操作数的值。例如,‘>’ 检查一个操作数是否大于另一个操作数,等等。结果返回一个布尔值,即 true 或 false。
示例
#include <iostream> using namespace std; int main() { int a = 6, b = 4; // Equal to operator cout << "a == b is " << (a == b) << endl; // Greater than operator cout << "a > b is " << (a > b) << endl; // Greater than or Equal to operator cout << "a >= b is " << (a >= b) << endl; // Lesser than operator cout << "a < b is " << (a < b) << endl; // Lesser than or Equal to operator cout << "a <= b is " << (a <= b) << endl; // true cout << "a != b is " << (a != b) << endl; return 0; }
输出
a == b is 0 a > b is 1 a >= b is 1 a < b is 0 a <= b is 0 a != b is 1
3. 逻辑运算符
这些运算符用于组合两个或多个条件或约束,或补充正在考虑的原始条件的评估。结果返回一个布尔值,即 true 或 false。
示例
#include <iostream> using namespace std; int main() { int a = 6, b = 4; // Logical AND operator cout << "a && b is " << (a && b) << endl; // Logical OR operator cout << "a || b is " << (a || b) << endl; // Logical NOT operator cout << "!b is " << (!b) << endl; return 0; }
输出
a && b is 1 a || b is 1 !b is 0
4. 位运算符
这些运算符用于对操作数执行位级运算。运算符首先转换为位级,然后对操作数执行计算。加法、减法、乘法等数学运算可以在位级执行,以实现更快的处理。
示例
#include <iostream> using namespace std; int main() { int a = 6, b = 4; // Binary AND operator cout << "a & b is " << (a & b) << endl; // Binary OR operator cout << "a | b is " << (a | b) << endl; // Binary XOR operator cout << "a ^ b is " << (a ^ b) << endl; // Left Shift operator cout << "a<<1 is " << (a << 1) << endl; // Right Shift operator cout << "a>>1 is " << (a >> 1) << endl; // One’s Complement operator cout << "~(a) is " << ~(a) << endl; return 0; }
输出
a & b is 4 a | b is 6 a ^ b is 2 a<<1 is 12 a>>1 is 3 ~(a) is -7
5. 赋值运算符
这些运算符用于为变量赋值。赋值运算符的左侧操作数是变量,赋值运算符的右侧操作数是值。右侧的值必须与左侧变量的数据类型相同,否则编译器将引发错误。
示例
#include <iostream> using namespace std; int main() { int a = 6, b = 4; // Assignment Operator cout << "a = " << a << endl; // Add and Assignment Operator cout << "a += b is " << (a += b) << endl; // Subtract and Assignment Operator cout << "a -= b is " << (a -= b) << endl; // Multiply and Assignment Operator cout << "a *= b is " << (a *= b) << endl; // Divide and Assignment Operator cout << "a /= b is " << (a /= b) << endl; return 0; }
输出
a = 6 a += b is 10 a -= b is 6 a *= b is 24 a /= b is 6
C++ 循环
循环语句用于以连续的方式遍历某些数据。循环广泛用于数据结构,例如数组、链表、图、树等等。这些是递归、动态规划和图论等高级概念的基础。循环语句主要有三种类型:
1. for循环
for循环用于遍历某个特定数据结构,在达到结束条件前运行特定次数。
示例
#include <iostream> using namespace std; int main() { for(int i=0;i<6;i++){ cout<<"hello"<<endl; } return 0; }
输出
hello hello hello hello hello hello
2. while循环
while循环用于运行循环语句,直到指定条件变为假,否则循环将持续运行。
示例
#include <bits/stdc++.h> using namespace std; int main() { int i=0; while(i<6){ cout<<"hello"<<endl; i++; } return 0; }
输出
hello hello hello hello hello hello
3. do-while循环
在do-while循环中,循环会在给定条件下第一次运行,然后检查while语句以决定是否继续运行。
示例
#include <bits/stdc++.h> using namespace std; int main() { int i=0; do{ cout<<"hello"<<endl; i++; }while(i<6); return 0; }
输出
hello hello hello hello hello hello
C++引用和指针
1. 引用
引用用于为同一个内存位置和存储在其上的值创建一个新名称。我们可以使用变量名旁边的地址符(&)来创建任何变量的引用。
示例
#include <bits/stdc++.h> using namespace std; int main() { int i=3; int &k=i; cout<<i<<k<<endl; return 0; }
输出
33
2. 指针
指针是用于存储其指向的变量地址的变量,使用*声明指向任何变量的指针。
示例
#include <bits/stdc++.h> using namespace std; int main() { int a=4; int *ptr=&a; cout<<a<<ptr<<*ptr<<endl; return 0; }
输出
40x7ffeb2bcfb0c4
C++ 数组
一个数组是相同数据类型的一系列元素,这些元素存储在存储器中连续的内存位置。数组可以在声明时指定或不指定元素的数量。
示例
#include <bits/stdc++.h> using namespace std; int main() { int arr1[]={1,2,3,4,4,3,2,1}; int arr2[8]={0}; for(int i=0;i<8;i++){ cout<<arr1[i]<<arr2[i]<<endl; } return 0; }
输出
10 20 30 40 40 30 20 10
多维数组
数组也可以定义为多维,所有元素的数据类型相同。
示例
#include <bits/stdc++.h> using namespace std; int main() { int arr[2][3]={{1,2,3},{4,4,3}}; for(int i=0;i<2;i++){ for(int j=0;j<3;j++){ cout<<arr[i][j]<<endl; } } return 0; }
输出
1 2 3 4 4 3
C++ 函数
函数是可以调用的代码部分,前提是它们已先前定义,有助于使代码简洁易读。函数可以作为程序的一部分创建,也可以在类体中创建。由C++编译器执行的第一个函数是main函数。
函数具有名称、返回类型(也可以是void)、输入变量和方法体。下面的示例展示了如何在C++中定义和使用函数。
C++中的函数可以分为两种类型:
- 基本函数,这些函数已在C++库中定义。基本函数的示例包括数学函数,如sin()、cos()、min()、max()等等。
- 用户自定义函数,根据用户的需求定义,可以相应地进行自定义。
示例
#include <bits/stdc++.h> using namespace std; void sum1(int &a, int &b){ b+=a; } int main(){ int a=10, b=12; sum1(a,b); cout<<b<<a<<endl; return 0; }
输出
2210
C++数学函数
C++作为C的超集,支持大量有用的数学函数。这些函数在标准C++中可用,以支持各种数学计算。
这些函数可以直接使用以简化代码和程序,而不必关注实现细节。要使用这些函数,需要包含头文件 - <math.h> 或 <cmath>。
以下示例展示了许多此类数学函数的使用,这些函数可以直接使用,而无需进行复杂的计算。
示例
#include <bits/stdc++.h> using namespace std; int main() { double x = 2.3; cout << "Sine value of x=2.3 : " << sin(x) << endl; cout << "Cosine value of x=2.3 : " << cos(x) << endl; cout << "Tangent value of x=2.3 : " << tan(x) << endl; double y = 0.25; cout << "Square root value of y=0.25 : " << sqrt(y) << endl; int z = -10; cout << "Absolute value of z=-10 : " << abs(z) << endl; cout << "Power value: x^y = (2.3^0.25) : " << pow(x, y) << endl; x = 3.0; y = 4.0; cout << "Hypotenuse having other two sides as x=3.0 and" << " y=4.0 : " << hypot(x, y) << endl; x = 4.56; cout << "Floor value of x=4.56 is : " << floor(x) << endl; x = -4.57; cout << "Absolute value of x=-4.57 is : " << fabs(x) << endl; x = 1.0; cout << "Arc Cosine value of x=1.0 : " << acos(x) << endl; cout << "Arc Sine value of x=1.0 : " << asin(x) << endl; cout << "Arc Tangent value of x=1.0 : " << atan(x) << endl; y = 12.3; cout << "Ceiling value of y=12.3 : " << ceil(y) << endl; x = 57.3; // in radians cout << "Hyperbolic Cosine of x=57.3 : " << cosh(x) << endl; cout << "Hyperbolic tangent of x=57.3 : " << tanh(x) << endl; y = 100.0; // Natural base with 'e' cout << "Log value of y=100.0 is : " << log(y) << endl; return 0; }
输出
Sine value of x=2.3 : 0.745705 Cosine value of x=2.3 : -0.666276 Tangent value of x=2.3 : -1.11921 Square root value of y=0.25 : 0.5 Absolute value of z=-10 : 10 Power value: x^y = (2.3^0.25) : 1.23149 Hypotenuse having other two sides as x=3.0 and y=4.0 : 5 Floor value of x=4.56 is : 4 Absolute value of x=-4.57 is : 4.57 Arc Cosine value of x=1.0 : 0 Arc Sine value of x=1.0 : 1.5708 Arc Tangent value of x=1.0 : 0.785398 Ceiling value of y=12.3 : 13 Hyperbolic Cosine of x=57.3 : 3.83746e+24 Hyperbolic tangent of x=57.3 : 1 Log value of y=100.0 is : 4.60517
C++面向对象编程
C++中也存在面向对象(OOP)概念。这基本上意味着程序可以细分为类和对象。
1. 类
类是一种用户定义的数据类型,具有两个组成部分:变量和方法。可以使用构造函数初始化类。
2. 对象
对象是类的实例或变量。对象在存储空间中占用内存。
3. 封装
封装将数据和方法封装在一个类或类别中。为此,使用类。
4. 抽象
这包括使用一定级别的安全性隐藏细节。
5. 多态
使用相同的名称和主体创建对象的多个实例或方法称为多态。
多态有以下类型:
1. 编译时多态
编译时多态可以通过以下方式实现:
2. 运行时多态
运行时多态可以通过以下方式实现:
- 函数重载
- 虚函数
6. 继承
将一个类(父类)的属性派生到另一个类(子类)称为继承。
C++ 文件处理
文件处理中的不同操作如下:
- 打开文件 - 要打开文件,请使用ofstream类的open()方法。
- 读取文件 - 要读取文件,请使用ifstream类的getline()方法。
- 写入文件 - 使用"<<"运算符在打开的文件中写入数据。
示例
#include <bits/stdc++.h> using namespace std; int main(){ ofstream outputFile("file1.txt"); // Open the file for writing outputFile.open("file1.txt"); if (outputFile.is_open()) { // Write data to the file outputFile << "Hello, World!" << endl; outputFile << 1333113 << endl; outputFile.close(); // Close the file }else { // Failed to open the file cout << "Error"<< endl; return 1; } // Reading from a file ifstream inputFile("file1.txt"); if (inputFile.is_open()) { string line; while (getline(inputFile, line)) { // Print each line cout << line << endl; } // Close the file inputFile.close(); }else { // Failed to open the file cout << "Error"<< endl; return 1; } return 0; }
C++ 异常处理
在使用类和对象时,由于用户编写的程序中存在某些错误或机器故障(例如内存或执行错误),可能会发生各种错误和异常。这些错误可能对程序的顺利执行造成致命影响,因此需要使用try和catch块进行处理。
当发生错误时,C++通常会停止并生成错误消息。该错误的专业术语是:C++会抛出异常(抛出错误)。
- Try块 - try语句允许你定义一段代码块,在执行期间对其进行错误测试。
- Throw - 当检测到问题时,throw关键字会抛出异常,这使我们能够创建自定义错误。
- Catch块 - catch语句允许你定义一段代码块,如果try块中发生错误,则执行该代码块。
Try-Catch异常处理语法
try { // Block of code to try throw exception; // Throw an exception when a problem arise } catch () { // Block of code to handle errors }
示例
#include <bits/stdc++.h> using namespace std; try { int bmi=30; if (bmi>28) { cout << "You are overweight."; } else { throw (bmi); } } catch (int x) { cout << "You are underweight."; cout << "Weight is: " << x; }
C++ 预处理器
预处理器是关键字,用于指示编译器在实际编译开始之前处理指令。这些关键字以‘#’开头,并且不需要在末尾使用‘;’,因为它们不是语句。
预处理器的示例包括#include、#define等等。
让我们看看C++库中重要的预处理器:
- #include
- #define
1. #include
它用于包含程序执行中使用的函数和方法所需的头文件和库。如前所述,不会显示方法的实际实现,只会显示最终结果。
示例
#include <math.h> #include <iostream> using namespace std; //the iostream is used for input and output stream of data //the math.h is used for including math functions like pow(x,y) int main(void){ cout<<pow(2,3); return 0; }
输出
8
2. #define
#define预处理器指令创建符号常量。符号常量称为宏,指令的一般形式是符号‘#’后跟define语句和需要定义的常量的定义。当此格式出现在文件中时,该文件中宏的所有后续出现都将在程序编译之前替换为替换文本。
示例
#include <bits/stdc++.h> using namespace std; #define A 45 //defining value of A as 45 int main(void){ int a= A; cout<<a; return 0; }
输出
45
C++ 命名空间
命名空间用于在一个程序中定义两个同名函数。这样,编译器就知道在调用函数时使用哪个方法。使用命名空间,你可以定义名称定义的上下文。本质上,命名空间定义了一个作用域。
定义命名空间很容易。你只需编写namespace后跟方法内部的代码即可。可以通过在函数名前提及命名空间以及中间的'::'符号来在程序内部使用此函数。
示例1
#include <bits/stdc++.h> using namespace std; // first name space namespace first_space { void func() { cout << "Inside first_space" << endl; } } // second name space namespace second_space { void func() { cout << "Inside second_space" << endl; } } int main () { // Calls function from first name space. first_space::func(); // Calls function from second name space. second_space::func(); return 0; }
输出
Inside first_space Inside second_space
using关键字可以以指令的形式使用,指示后续代码遵循提到的命名空间。类似地,'std'关键字用于说明所有代码都将遵循标准命名空间。
要了解有关命名空间的更多信息,请参阅本文 - C++中的命名空间
示例2
#include <bits/stdc++.h> using namespace std; // first name space namespace first_space { void func() { cout << "Inside first_space" << endl; } } // second name space namespace second_space { void func() { cout << "Inside second_space" << endl; } } using namespace first_space; int main () { // Calls function from first name space. func(); return 0; }
输出
Inside first_space
C++ 模板
模板是创建泛型类或函数的蓝图或公式。库容器(如迭代器和算法)是使用模板概念开发的。
C++中提供两种类型的模板:
- 类模板
- 函数模板
1. 类模板
类模板可用于定义不同的数据结构,如链表、栈、队列、优先队列、树等等。类模板可以按以下方式定义:
语法
template <class type> class class-name { . . . }
示例
#include <bits/stdc++.h> using namespace std; template <typename T> class Array { T* pointer; int size; public: Array(T a[], int s); void show(); }; template <typename T> Array<T>::Array(T a[], int s){ pointer = new T[s]; size = s; for (int i = 0; i < size; i++) pointer[i] = a[i]; } template <typename T> void Array<T>::show(){ for (int i = 0; i < size; i++) cout << *(pointer + i)<<endl; cout << endl; } int main(){ int size=7; int a[size] = { 12, 21, 45, 34, 19, 55, 66 }; Array<int> a1(a, 7); a1.show(); return 0; }
输出
12 21 45 34 19 55 66
2. 函数模板
这些可用于使用模板库创建泛型函数,这些库具有内置功能。函数模板的一些示例包括max()、min()、sin()、floor()等等。
示例
#include <bits/stdc++.h> using namespace std; template <typename T> T minof3(T x, T y, T z){ if(x<y && x<z) return x; if(y<x && y<z) return y; if(z<x && z<y) return z; // else return "Not applicable !!!"; } int main(){ // Call minof3 for int cout << minof3<int>(32,58,97) << endl; // call minof3 for double cout << minof3<double>(13.0,12.0, 17.0) << endl; // call minof3 for char cout << minof3<char>('g', 'e', 't') << endl; // call minof3 for string cout << minof3<string>("apple", "ball", "cat")<<endl; return 0; }
输出
32 12 e apple
C++ 动态内存
C++中的内存分为两部分:
- 栈内存 - 在函数内部声明的所有变量都将占用来自栈的内存。
- 堆内存 - 这是程序的未用内存,可以在程序运行时动态分配内存。
在编写程序时,有时可能会出现事先不知道所需内存的情况,因此在运行时需要从堆内存中获取额外的空间。这就是动态内存分配,可以使用'new'关键字实现。利用完此空间后,可以使用'delete'关键字释放数据。
来自C的malloc()函数仍然存在于C++中,但建议避免使用malloc()函数。new优于malloc()的主要优点在于,new不仅分配内存,还构造对象,这是C++的主要目的。
示例
#include <bits/stdc++.h> using namespace std; int main () { int *ptr = NULL; // Pointer initialized with null ptr = new int; // Request memory for the variable *ptr = 31; // Store value at allocated address cout << "Value of pointer : " << *ptr << endl; delete ptr; // free up the memory. return 0; }
输出
Value of pointer : 31
类似地,在实现数组和类时也可以动态分配内存。有关动态内存分配的更多信息,请参阅有关动态内存分配的文章。
C++ 信号处理
信号处理是在程序执行期间控制传递的中断信号的过程。存在各种中断,这些中断可能会过早终止程序并产生不同的响应。例如,在Linux/Unix命令行界面(CLI)中,'CTRL+C'命令会生成结束程序中断。类似地,C++编程语言中也存在许多中断。这些中断在<csignal>库中定义。
序号 | 信号和描述 |
---|---|
1 | SIGABRT 程序异常终止,例如调用abort。 |
2 | SIGFPE 算术运算错误,例如除以零或导致溢出的运算。 |
3 | SIGILL 检测到非法指令。 |
4 | SIGINT 收到交互式注意信号。 |
5 | SIGSEGV 存储器访问无效。 |
6 | SIGTERM 发送到程序的终止请求。 |
1. signal()函数
signal函数由<csignal>库提供,用于立即捕获不需要的或错误的中断。以下是signal()函数的使用方法,它接受两个输入,第一个是信号编号,第二个是信号处理函数。
示例
#include <csignal> #include <iostream> using namespace std; void handler_func(int signal_num){ cout << endl<<"You have interrupted: (" << signal_num << "). \n"; //using exit to terminate exit(signal_num); } int main(){ //initialize signal signal(SIGABRT, handler_func); while (true) { cout << "You can't stop me !!!" << endl; this_thread::sleep_for(chrono::seconds(1)); //this is used for delay } return 0; //press ctrl+c to interrupt the program execution!!! }
2. raise() 函数
signal 函数由 <csignal> 库提供,用于生成带有其编号的中断。以下是 raise() 函数的使用方法,它接收一个输入,即信号编号。
示例
#include <csignal> #include <iostream> using namespace std; void signal_handler(int signum){ cout << "You generated this interrupt: (" << signum << ").\n"; // terminate program exit(signum); } int main(){ int i = 0; signal(SIGABRT, signal_handler); while (++i) { cout << "You can't stop me !!!" << endl; if (i == 10) raise(SIGABRT); } return 0; }
C++ 多线程
多线程是操作系统在处理器上进行多任务处理的概念的一部分。多任务处理通常细分为两部分——基于进程和基于线程。
在基于进程的多任务处理中,两个或多个进程或程序在执行时并发运行在处理器上,并且完全依赖于处理器的能力来处理任务。
在基于线程的多任务处理中,每个程序被划分为多个线程,可以将其视为在处理器上并发运行并一起生成响应的较小的子程序。因此,多个线程组合在一起形成一个程序。这被称为多线程。
在 C++ 中,在 C++ 11 发布之前,没有内置的多线程支持。C++ 使用 POSIX 线程,或 Pthreads,它们在许多类 Unix POSIX 系统上可用。可以在 pthreads 上执行以下操作:
- 创建线程
- 终止线程
- 向线程传递参数
- 连接和分离线程
创建线程
可以使用 <pthread.h> 库中的 pthread_create 例程创建线程。这些可以在程序中的任何位置创建。
语法
#include <pthread.h> pthread_create (thread, attr, start_routine, arg);
序号 | 参数 & 描述 |
---|---|
1 |
thread 子程序返回的新线程的不透明唯一标识符。 |
2 |
attr 一个不透明的属性对象,可用于设置线程属性。您可以指定一个线程属性对象,或使用 NULL 表示默认值。 |
3 |
start_routine 线程创建后将执行的 C++ 例程。 |
4 |
arg 可以传递给 start_routine 的单个参数。它必须作为 void 类型的指针强制转换进行引用传递。如果不需要传递参数,可以使用 NULL。 |
终止线程
pthread_exit() 用于在线程完成执行并且不再需要在程序中时终止线程。这有助于清除最初分配给线程的空间。
语法
#include <pthread.h> pthread_exit (status);
示例
#include <iostream> #include <cstdlib> #include <pthread.h> using namespace std; #define NUM_THREADS 5 void *PrintHello(void *threadid) { long tid; tid = (long)threadid; cout << "Hello World! Thread ID, " << tid << endl; pthread_exit(NULL); } int main () { pthread_t threads[NUM_THREADS]; int rc; int i; for( i = 0; i < NUM_THREADS; i++ ) { cout << "main() : creating thread, " << i << endl; rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i); if (rc) { cout << "Error:unable to create thread," << rc << endl; exit(-1); } } pthread_exit(NULL); }
输出
main() : creating thread, 0 main() : creating thread, 1 Hello World! Thread ID, 0 main() : creating thread, 2 Hello World! Thread ID, 1 main() : creating thread, 3 Hello World! Thread ID, 2 main() : creating thread, 4 Hello World! Thread ID, 3 Hello World! Thread ID, 4
连接和分离线程
以下例程用于在程序中连接和分离线程:
语法
pthread_join (threadid, status) pthread_detach (threadid)
示例
#include <iostream> #include <cstdlib> #include <pthread.h> #include <unistd.h> using namespace std; #define NUM_THREADS 5 void *wait(void *t) { int i; long tid; tid = (long)t; sleep(1); cout << "Sleeping in thread " << endl; cout << "Thread with id : " << tid << " ...exiting " << endl; pthread_exit(NULL); } int main () { int rc; int i; pthread_t threads[NUM_THREADS]; pthread_attr_t attr; void *status; // Initialize and set thread joinable pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for( i = 0; i < NUM_THREADS; i++ ) { cout << "main() : creating thread, " << i << endl; rc = pthread_create(&threads[i], &attr, wait, (void *)i ); if (rc) { cout << "Error:unable to create thread," << rc << endl; exit(-1); } } // free attribute and wait for the other threads pthread_attr_destroy(&attr); for( i = 0; i < NUM_THREADS; i++ ) { rc = pthread_join(threads[i], &status); if (rc) { cout << "Error:unable to join," << rc << endl; exit(-1); } cout << "Main: completed thread id :" << i ; cout << " exiting with status :" << status << endl; } cout << "Main: program exiting." << endl; pthread_exit(NULL); }
输出
main() : creating thread, 0 main() : creating thread, 1 main() : creating thread, 2 main() : creating thread, 3 main() : creating thread, 4 Sleeping in thread Thread with id : 0 ...exiting Sleeping in thread Thread with id : 2 ...exiting Sleeping in thread Thread with id : 1 ...exiting Main: completed thread id :0 exiting with status :0 Sleeping in thread Main: completed thread id :1 exiting with status :0 Main: completed thread id :2 exiting with status :0 Thread with id : 4 ...exiting Sleeping in thread Thread with id : 3 ...exiting Main: completed thread id :3 exiting with status :0 Main: completed thread id :4 exiting with status :0 Main: program exiting.
向线程传递参数
以下程序演示了如何使用多线程在线程中传递参数和语句。
示例
#include <iostream> #include <cstdlib> #include <pthread.h> using namespace std; #define NUM_THREADS 5 struct thread_data { int thread_id; char *message; }; void *PrintHello(void *threadarg) { struct thread_data *my_data; my_data = (struct thread_data *) threadarg; cout << "Thread ID : " << my_data->thread_id ; cout << " Message : " << my_data->message << endl; pthread_exit(NULL); } int main () { pthread_t threads[NUM_THREADS]; struct thread_data td[NUM_THREADS]; int rc; int i; for( i = 0; i < NUM_THREADS; i++ ) { cout <<"main() : creating thread, " << i << endl; td[i].thread_id = i; td[i].message = "This is message"; rc = pthread_create(&threads[i], NULL, PrintHello, (void *)&td[i]); if (rc) { cout << "Error:unable to create thread," << rc << endl; exit(-1); } } pthread_exit(NULL); }
输出
main() : creating thread, 0 main() : creating thread, 1 main() : creating thread, 2 Thread ID : 0 Message : This is message Thread ID : 1 Message : This is message main() : creating thread, 3 Thread ID : 2 Message : This is message main() : creating thread, 4 Thread ID : 3 Message : This is message Thread ID : 4 Message : This is message
自诞生以来,C++ 编程 世界发生了很多变化,了解正在引入的新语法变得越来越重要。本文总结了 C++ 中最流行的语法,旨在为编程之旅初学者奠定所有基础。对于更有经验的开发者,本文将概述 C++ 世界中正在发生的事情。