0
点赞
收藏
分享

微信扫一扫

(c++)new的用法

Hyggelook 2022-04-26 阅读 96
c++
//new的用法
#include<iostream>
using namespace std;
int main()
{
    int *a=new int(5);//输出:5
    cout<<*a<<" "<<endl;

    int *b=new int[5]{0};
    for(int i=0;i<5;i++)
        cout<<b[i]<<" ";//输出: 0 0 0 0 0
    cout<<endl;

    int *c=new int[5]{0,1,2,3,4};
    for(int i=0;i<5;i++)
        cout<<c[i]<<" ";//输出: 0 1 2 3 4
    cout<<endl;

    struct Test1{
        string name;
        int age;
        struct  Test1 *next;
    };

    Test1 *d=new Test1();//自动初始化 name="",age=0,next=NULL; 
    d->name="xiaoming",d->age=18,d->next=NULL;
    cout<<"name:"<<d->name<<" age:"<<d->age<<" next:"<<d->next<<endl;

    class Test2{
        public:
        string name;
        int age;
        Test2 *next;

        public:
            Test2(){this->name="",this->age=0,this->next=NULL;}
            Test2(string name){
                this->name=name;
                this->age=0;
            }
            Test2(int age){
                this->age=age;
            }
            Test2(string name,int age){
                this->name=name;
                this->age=age;
            }
    };

    Test2 *e=new Test2();
    cout<<e->name<<"+"<<e->age<<endl;//输出:+0

    string name="xiaoming";
    int age=18;

    Test2 *f=new Test2(name);
    cout<<f->name<<"+"<<f->age<<endl;//输出:xiaoming+0

    Test2 *g=new Test2(age);
    cout<<g->name<<"+"<<g->age<<endl;//输出:+18;

    Test2 *h=new Test2(name,age);
    cout<<h->name<<"+"<<h->age<<endl;//输出:xiaoming+18;
}
    
举报

相关推荐

C++new用法详解

C++ new/delete

C++——定位new

C++ new/delete的重载

0 条评论