zoukankan      html  css  js  c++  java
  • 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;
    }

  • 相关阅读:
    k8s中文网
    python range用法
    python 日志滚动 分文件
    python 语法
    flask 中文编码解码
    python的杨辉三角
    mysql8.0.4以后修改密码方式变更
    flask学习视频
    oralce的lag和lead函数
    JNI 各类数据类型处理
  • 原文地址:https://www.cnblogs.com/liming19680104/p/13488504.html
Copyright © 2011-2022 走看看