單位加強(qiáng)網(wǎng)站建設(shè)網(wǎng)絡(luò)推廣自學(xué)
模板
模板是C++中一種強(qiáng)大的特性,允許你編寫通用的代碼,以便在不同數(shù)據(jù)類型上重復(fù)使用。模板分為函數(shù)模板和類模板,它們都是在編譯時(shí)生成具體代碼的藍(lán)圖。
函數(shù)模板
函數(shù)模板是一種定義通用函數(shù)的方式,可以在不同數(shù)據(jù)類型上使用相同的代碼邏輯。函數(shù)模板使用template
關(guān)鍵字定義,允許在函數(shù)中使用一個(gè)或多個(gè)類型參數(shù)。
語(yǔ)法
template <typename T>
return_type function_name(T parameter1, T parameter2, ...) {// 函數(shù)體
}
template <typename T>
:定義了一個(gè)模板,其中T
是類型參數(shù),可以在函數(shù)內(nèi)部使用。return_type
:函數(shù)的返回類型。function_name
:函數(shù)的名稱。T parameter1, T parameter2, ...
:函數(shù)的參數(shù)列表,參數(shù)的類型是T
。
示例
#include <iostream>// 函數(shù)模板示例:計(jì)算兩個(gè)數(shù)的最大值
template <typename T>
T max(T a, T b) {return (a > b) ? a : b;
}int main() {int x = 5, y = 10;double d1 = 3.5, d2 = 7.8;std::cout << "Max of integers: " << max(x, y) << std::endl;std::cout << "Max of doubles: " << max(d1, d2) << std::endl;return 0;
}
類模板
類模板允許你定義通用的類,其中的數(shù)據(jù)類型可以作為參數(shù)進(jìn)行指定,以便創(chuàng)建適用于不同數(shù)據(jù)類型的對(duì)象。
語(yǔ)法
template <typename T>
class ClassTemplate {
public:// 類成員和方法
};
template <typename T>
:定義了一個(gè)類模板,其中T
是類型參數(shù),可以在類內(nèi)部使用。
示例
#include <iostream>// 類模板示例:實(shí)現(xiàn)一個(gè)通用的棧
template <typename T>
class Stack {
private:T* data;int top;int capacity;public:Stack(int size) : capacity(size), top(-1) {data = new T[capacity];}~Stack() {delete[] data;}void push(T value) {if (top < capacity - 1) {data[++top] = value;}}T pop() {if (top >= 0) {return data[top--];}return T(); // 默認(rèn)構(gòu)造一個(gè)T類型的對(duì)象并返回}bool isEmpty() {return top == -1;}
};int main() {Stack<int> intStack(5);Stack<double> doubleStack(3);intStack.push(10);intStack.push(20);doubleStack.push(3.14);std::cout << "Int Stack: ";while (!intStack.isEmpty()) {std::cout << intStack.pop() << " ";}std::cout << std::endl;std::cout << "Double Stack: ";while (!doubleStack.isEmpty()) {std::cout << doubleStack.pop() << " ";}std::cout << std::endl;return 0;
}
注意
模板聲明和實(shí)現(xiàn)必須放在同一個(gè)文件中
因?yàn)閏++模板的底層是占位符,編譯的時(shí)候鏈接編入,如果放在不同文件,調(diào)用會(huì)出現(xiàn)找不到定義/實(shí)現(xiàn)的情況