模板程式設計學習注意點

2021-07-09 14:01:23 字數 2516 閱讀 3518

最近剛開始學習模板程式設計,有些注意點

1.在類模板程式設計中對操作符《進行過載時,類中宣告時需要使用

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

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

這個意思指在容器執行插入元素操作時,是把元素拷貝乙份放在容器中,而不是引用物件。所以stl容器內儲存的元素必須是能夠被拷貝的(如果物件中存在指標型別的成員變數,則需要支援深拷貝)

下面是我寫了乙個簡單的myvector類模板,並且寫了乙個teacher類,大家可以拷過去看看,應該會更加清楚

------------------myvector.h
#pragma once

#includeusing namespace std;

templateclass myvector

;

------------------myvector.hpp
#include#include"demo9.h"

#include"teacher.h"

using namespace std;

templateostream& operator<< (ostream &out, const myvector&obj)

out << endl;

return out;

}templatemyvector::myvector(int size=0)

templatemyvector::myvector(const myvector& obj) }

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

templatemyvector::~myvector()

}templatet& myvector::operator(int index)

templateint myvector::getvectorsize()

------------------teacher.h
#pragma once

#includeusing namespace std;

class teacher

;

------------------teacher.cpp

#include#include"teacher.h"

#includeusing namespace std;

teacher::teacher()

teacher::teacher(char *name, int age)

void teacher::printt()

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

teacher::teacher(const teacher &obj)

teacher& teacher::operator=(const teacher &obj)

ostream & operator<<(ostream& out, const teacher * obj)

------------------main.cpp
#include#include"demo9.hpp"

#include"teacher.h"

void main()

cout <<"tarray"<< tarray;

cout << "***************************" << endl;

cout << "marray" << *marray;

cout << "---------------------------" << endl;

cout << "narray" << narray;

delete marray;

cout << "+++++++++++++++++++++++++++" << endl;

teacher t5("xbb", 20), t6("sddf", 30), t7("dsd", 60);

myvectorparray(3);

parray[0] = &t5;

parray[1] = &t6;

parray[2] = &t7;

cout << parray << endl;

system("pause");

}

C 程式設計注意點

1.strcpy 是碰到 0就會停止拷貝的,最好使用memcpy和strncpy代替。2.memset並不分配記憶體,malloc才分配。3.迴圈裡面要注意出錯的地方sleep 4.匈牙利命名法 5.臨時變數也要有意義 6.控制代碼要注意釋放,特別是在出錯的地方 7.memset不能過於頻繁 8.物...

asp程式設計注意點

一 asp中,如果在檔案頭加入 option explicit 則表示該程式中的所有變數都必須 先定義,即dim varia,然後才能使用。今天在用aspjpeg 2.0做後台壓縮,結果執行到set jpeg server.createobject persits.jpeg 時,無論如何都不行。解決...

GDI程式設計注意點 1

textout的屬於比較老的文字輸出函式,但是簡單的文字輸出和格式控制使用它非常方便,廢話不多說,基本用法如下 void drawarea1 cdchandle mydc,point ptlefttop,point ptrightbottom 效果如下 可以看到,1.使用setbkmode決定背景是...