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

 

 

 

 

C++创建对象和销毁对象

相关文章:

  • 2021-11-02
  • 2022-01-08
  • 2021-07-16
  • 2021-12-27
  • 2021-07-19
  • 2022-03-05
  • 2022-12-23
猜你喜欢
  • 2022-01-07
  • 2021-11-03
  • 2021-12-02
  • 2021-10-14
相关资源
相似解决方案