類模板在專案開發中的應用

2021-07-23 05:48:55 字數 2254 閱讀 9310

模板是c++型別引數化的多型工具。c++提供函式模板和類模板。

模板定義以模板說明開始。類屬引數必須在模板定義中至少出現一次。

同乙個類屬引數可以用於多個模板。

類屬引數可用於函式的引數型別、返回型別和宣告函式中的變數。

模板由編譯器根據實際資料型別例項化,生成可執行**。例項化的函式。

模板稱為模板函式;例項化的類模板稱為模板類。

函式模板可以用多種方式過載。

類模板可以在類層次中使用 。

訓練題1) 請設計乙個陣列模板類( myvector ),完成對int

、char

、teacher

型別元素的管理。

需求設計:

類模板建構函式 拷貝建構函式 <<  過載=

操作符

a2=a1

實現2) 請仔細思考:

a) 如果陣列模板類中的元素是teacher

元素時,需要

teacher

類做什麼工作

b) 如果陣列模板類中的元素是teacher

元素時,

teacher

類含有指標屬性哪?

結論1: 如果把

teacher

放入到myvector

陣列中,並且

teacher

類的屬性含有指標,就是出現深拷貝和淺拷貝的問題。

結論2:需要teacher

封裝的函式有:

1) 重寫拷貝建構函式  

2) 過載等號操作符  

3) 過載左移操作符。

理論提高:所有容器提供的都是值(value)語意,而非引用(reference)語意。容器執行插入元素的操作時,內部實施拷貝動作。所以stl容器內儲存的元素必須能夠被拷貝(必須提供拷貝建構函式)。

實現**:

myvector.h

#pragma once

#include using namespace std;

templateclass myvector

friend ostream& operator<< (ostream&out,const myvector&obj);

protected:

t *m_space;

int m_len;

};

myvector.cpp

#include "myvector.h"

templatemyvector::myvector(int size)

templatemyvector::myvector(const myvector&obj)

}templatet& myvector::operator(int index)

templatemyvector& myvector::operator=(const myvector&obj)

m_len = obj.m_len;

m_space = new t[m_len];

for (int i =0;iostream& operator<< (ostream&out,const myvector&obj)

teacher(int age,char*name)

teacher(const teacher&obj)

~teacher() }

void printt()

int len = strlen(obj.name)+1;

this->name = new char[len];

memcpy(this->name,obj.name,len);

this->age = obj.age;

return *this; }

protected:

private:

int age;

char *name;

}; ostream& operator<< (ostream&out,const teacher &obj)

coutmyv4[0] = &t1;

myv4[1] = &t2;

myv4[2] = &t3;

myv4[3] = &t4;

myv4[4] = new teacher(38,"abc");

for (int i=0;i<5;i++)

system("pause");

return 0;

}

類簇在iOS開發中的應用

類簇 class cluster 是一種設計模式,在foundation framework中被廣泛使用,舉個簡單的例子 nsarray arr nsarray arraywithobjects foo bar nil nslog arr class arrclass output nsarrayi...

UML在軟體專案開發中的詳細應用

大多數做軟體開發的人員都知道uml,但uml如何才能在軟體專案開發中發揮它的巨大作用呢?下面就專案不同階段的特殊 情形的特殊要求來講一下uml的運用。uml在軟體不同階段中的應用 一 需求分析階段 開發軟體的過程中,在需求分析階段最大的任務就是 要搞清楚使用者需要我們開發的軟體來做什麼,軟體有什麼功...

NVelocity模板引擎在專案中的應用

本文要說明的是如果要在專案中加入nvelocity引擎模板。而且在使用和操作起來更加的方便!nvelocity是乙個基於.net的模板引擎 template engine 它允許任何人僅僅簡單的使用模板語言 template language 來引用由.net 定義的物件。至於其他的一些別的nvel...