Assertion
Header file: #include <assert.h>
An assertion is a statement that must be true for the fuction to be correct
(程式發展時,去使用來檢測)
assert(判斷式)
如果判斷式正確 就會執行下段程式
不正確 就會出現提示
Constructors & Destructors
Constructor建構函式(或稱建構子)通常和類別名稱一樣
會在物件被初始化(就是被"創造")時執行
可以被過載(Overloading)以備用來生成不同種類的物件
但沒有型態(void, int, char, bool)所以沒有傳回值
Constructor的功能是用來生成物件,
並在物件生成時定義一些你要定義的東西
Destructor解構函式用來進行一些善後的工作
例如:
清除動態配置的記憶體,檔案的儲存、撰寫記錄檔等等
Destructor和類別同名,但特別的是在前面加上"~"
且沒有型態,沒有傳回值,不能被過載
程式會自動在最後一行之後呼叫Destructor
Initialization List
ex Dog::Dog(const char *name,const Breed,const int age)
:m_age(age),m_name(new char[strlen(name)+1]),m_breed(breed)
{
strcpy(m_name,name);
}
:m_age(age),m_name(new char[strlen(name)+1]),m_breed(breed)
↑third ↑ first ↑second
順序和排列無關,和class裡面定義的順序有關
ex 01 #include <iostream>
02 #include <vector>
03 #include <string>
04 using namespace std;
05
06 int main()
07 {
08 ifstream inf("inputData.txt");
09 string line;
10 vector<string> lines;
11
12 while (getline(inf, line))
13 lines.push_back(line);
14
15 for (int i=0; i<lines.size(); i=i+2)
16 cout << i << ":" << lines[i] << endl;
17
18 return 0;
19 }
請問在程式中哪些地方可能有呼叫建構元函式?
第 8 列呼叫 ifstream(char *) 或是 ifstream(string) 建構元函式 1 次
第 9 列呼叫 string() 建構元函式 1 次
第 10 列呼叫 vector<string>() 建構元函式 1 次
第 13 列呼叫 string(string &) 建構元函式 12 次
第 18 列之前會反序解構 12 次 string 類別的物件lines[i],呼叫 ~string() 解構元
解構 1 次 vector<string> 類別的物件 lines
解構 1 次 string 類別的物件 line
解構 1 次 ifstream 類別的物件 inf
補充stati
類別內static 變數的性質為:
這個變數是所有此類別物件共享的,
唯一的一個變數, 這個變數所使用
的記憶體不是在產生物件時配置的, 也不會
在任何一個物件解構時刪除, 它的記憶體是
在cpp檔案中另外定義的,這種變數是用來儲存
所有此類別物件通用的屬性,或是記錄一些共通的常數
--
▄▄▄▄▄
▄▄ ▄▄ ▄
▄▄▄▄▄▄▄▄▄▄▄
▄▄▄▄▄▄ ▄▄▄▄▄▄
▄▄▌██▌█▌▌ ▌▌▄▌
▄▌█▄▄▄▄█▄▄▄▄▄▌█▄
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 122.116.81.45