
- 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++ 世界中正在發生的事情。