1. 程式人生 > >《C++語言程式設計基礎》學習之模板與群體資料

《C++語言程式設計基礎》學習之模板與群體資料

 函式模板: 如果過載的函式,其解決問題的邏輯是一致的、函式體語句相同,只是處理的資料型別不同,那麼寫多個相同的函式體,是重複勞動,而且還可能因為程式碼的冗餘造成不一致性。

template<typename T>
T abs(T x) {
	return x < 0 ? -x : x;
}
int main(){
	int n = -5;//編譯器根據實參的型別推匯出模板T的型別
	double d = -5.5;
	cout << abs(n) << endl;
	cout << abs(d) << endl;
	return 0;
}

函式模板定義語法:語法形式: template <模板引數表>函式定義: 模板引數表的內容:型別引數:class(或typename) 識別符號,常量引數:型別說明符 識別符號,模板引數:template <引數表> class識別符號 注意:一個函式模板並非自動可以處理所有型別的資料;只有能夠進行函式模板中運算的型別,可以作為型別實參;自定義的類,需要過載模板中的運算子,才能作為型別實參。

template <class T> //定義函式模板
void outputArray(const T*array, int count) {
	for (int i = 0; i < count; i++)
		//如果陣列元素是類的物件,需要該物件所屬類過載了流插入運算子“<<”
		cout << array[i] << " ";
	cout << endl;
}
int main(){
	const int A_COUNT = 9, B_COUNT = 9, C_COUNT = 10;
	int a[A_COUNT] = { 1,2,3,4,5,6,7,8,9 };
	double b[B_COUNT] = { 1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9 };
	char c[C_COUNT] = "Welcome!";

	cout << " a array contains: " << endl;
	outputArray(a, A_COUNT);
	cout << " b array contains: " << endl;
	outputArray(b, B_COUNT);
	cout << " c array contains: " << endl;
	outputArray(c, C_COUNT);
	return 0;
}

類模板:類模板的作用:使用類模板使使用者可以為類宣告一種模式,使得類中的某些資料成員、某些成員函式的引數、某些成員函式的返回值,能取任意型別(包括基本型別的和使用者自定義型別)。類模板的宣告:類模板 template <模板引數表> class 類名 {類成員宣告};如果需要在類模板以外定義其成員函式,則要採用以下的形式: template <模板引數表> 型別名 類名<模板引數識別符號列表>::函式名(引數表)

struct Student {
	int id; //學號
	float gpa;//平均分
};
template <class T>
class Store {//類模板:實現對任意型別資料進行存取
private:
	T item;//item用於存放任意型別的資料
	bool haveValue;//haveValue標記item是否已被存入內容
public:
	Store();
	T &getElem();//提取資料函式
	void putElem(const T&x);//存入資料函式
};
template<class T>
Store<T>::Store() :haveValue(false) {}
template<class T>
T &Store<T>::getElem() {
	//如試圖提取未初始化的資料,則終止程式
	if (!haveValue) {
		cout << "No item present!" << endl;
		exit(1);//使程式完全退出,返回到作業系統。
	}
	return item;//返回item中存放的資料
}
template<class T>
void Store<T>::putElem(const T&x) {
	//將havaValue置為true,表示item中已存入數值
	haveValue = true;
	item = x;//將x值存入item
}
int main() {
	Store<int> s1, s2;
	s1.putElem(3);
	s2.putElem(-7);
	cout << s1.getElem() << " " << s2.getElem() << endl;

	Student g = { 1000,23 };
	Store<Student> s3;
	s3.putElem(g);
	cout << "The student id is " << s3.getElem().id << endl;

	Store<double> d;
	cout << "Retrieving object D... ";
	cout << d.getElem() << endl;
	//d未初始化,執行函式D.getElement()時導致程式終止
	return 0;
}