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

  • 相关阅读:
    xamp配置多域名站点
    POJ1611-The Suspects-ACM
    POJ2524-宗教问题-并查集-ACM
    POJ3274-牛的属性-HASH-ACM
    拓扑排序-DFS
    拓扑排序
    POJ1007-DNA Sorting-ACM
    POJ1258-Agri-Net-ACM
    wdcp-apache配置错误导致进程淤积进而内存吃紧
    wdcp-apache开启KeepAlive提高响应速度
  • 原文地址:https://www.cnblogs.com/liming19680104/p/13488504.html
Copyright © 2011-2022 走看看