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; }
标签:销毁,no,int,who,创建对象,C++,Student,no1 来源: https://www.cnblogs.com/liming19680104/p/13488504.html