C++建立物件和銷燬物件
阿新 • • 發佈:2020-08-12
#include <iostream> #include <string> using namespace std; class Student { public: Student(const string& name1, int age1, int no1) { name = name1; age = age1; no = no1; } private: string name; public: int age; int no; void who(void) { cout << "我叫" << name << endl; cout << "今年" << age << "歲" << endl; cout << "學號是:" << no << endl; } }; int main() { Student s("張三",25,10011); //在棧區建立單個物件格式一 //Student s 如果是無參--沒有括號 s.who(); Student s1= Student("李四", 26, 10012); //在棧區建立單個物件格式二 //單個引數時,後面的類名可以省略,比如:string str="liming" s1.who(); //在棧區建立多個物件--物件陣列 Student ss[2] = { Student("張三三",25,10013),Student("李四四",25,10014) }; ss[0].who(); Student* d = new Student("趙雲", 29, 10015);//在堆區建立單個物件--物件指標 //new操作符會先分配記憶體再呼叫建構函式,完成物件的建立和初始化;而如果是malloc函式只能分配記憶體,不會呼叫建構函式,不具備建立物件能力d->who(); delete d; //銷燬單個物件 Student* p = new Student[2]{ //在堆區建立多個物件--物件指標陣列 Student("劉備",40,10016),Student("劉徹",45,10017) }; p[0].who(); delete[] p; //銷燬 return 0; }