Linux下C++學習第6天,molloc與new和初始化列表
阿新 • • 發佈:2021-01-30
molloc與new
建立物件的步驟:1、申請空間 2、呼叫建構函式初始化
在C++中,malloc是不會執行建構函式的,他只是實現了記憶體的分配,所以C++中不用malloc建立物件
free同樣也是在釋放記憶體,不會銷燬物件資源。C++中使用new來建立物件(建立物件的同時會呼叫建構函式),用delete來刪除物件(同時呼叫解構函式)。
#include <iostream> #include <cstdlib> using namespace std; class Test { public: Test() { cout << "Test建構函式" << endl; } ~Test() { cout << "Test解構函式" << endl; } }; int main() { //Test t1; //棧空間建立物件 //建立物件 1、申請空間 2、呼叫建構函式初始化 C++中不用malloc建立物件 Test *pt = (Test *)malloc(sizeof(Test) * 1);//在堆空間申請一個物件大小的記憶體 if (NULL == pt) { cout << "malloc failure" << endl; } free(pt); //釋放記憶體, 不是釋放物件 Test *pt2 = new Test; // 申請堆記憶體, 呼叫建構函式 自動呼叫建構函式 delete pt2; //呼叫解構函式 return 0; }
關於new,delete的用法
#include <iostream> using namespace std; class Test { public: Test() { cout << " 無參建構函式" <<endl; } Test(int a, int b) { cout << "有參建構函式" << endl; } ~Test() { cout << " 解構函式" << endl; } }; int main() { int *p1 = new int; //給一個整數申請空間 cout << *p1 << endl; delete p1; char *p2 = new char; //給一個字元申請空間 delete p2; int *p3 = new int(100);//給一個整數申請空間同時初始化為100 cout << *p3 << endl; delete p3; char *p4 = new char[10];//給十個字元申請空間 delete[] p4; Test *t1 = new Test; delete t1; Test *t2 = new Test(1, 2); delete t2; return 0; }
初始化列表適用環境: 1、類物件作為成員變數並且該類並沒有提供無參建構函式 2、成員變數被const修飾(初始化和賦值不同)
初始化列表總結:
1、初始化列表要優先於當前物件的建構函式先執行
2、子物件的初始化順序和其在初始化列表的排列順序無關,但和在類中的宣告順序有關,先宣告的先初始化
3、解構函式的呼叫順序與建構函式相反
4、初始化const成員變數,初始化const成員變數的唯一辦法就是使用引數初始化表
#include <iostream> using namespace std; class Data { private: int year; int mouth; int day; public: Data(int y, int m, int d) { year = y; mouth = m; day = d; } }; //物件初始化列表: 1、類物件作為成員變數並且該類並沒有提供無參建構函式 // 2、成員變數被const修飾(初始化和賦值不同) class Student { const int id; //const聲明後,ID中不能被修改,且是垃圾值,無用。所以需要列表初始化他。(id這類資訊是怎麼樣的一類資訊呢,為什麼const修飾呢,就跟每個人身份證一樣,初始化一般不容修改,所以用const修飾) Data birth; public: Student(int i, int y, int m, int d) : birth(y, m, d), id(i) //其實可以這麼理解:對上述宣告進行賦值 方法是物件名或者變數名(值) ;然後建構函式中命名的類中貼上這些內容。 { } }; int main() { Student s1(1,1992,0,0); return 0; }