C++創建對象和銷毀對象


 

#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;
}

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM