对象的动态建立和释放

用new运算符动态分配内存后,将返回一个指向新对象的指针,即所分配的内存空间的起始地址,可以得到这个地址来访问这个对象

因此需要一个指向本类对象的指针变量来存放此地址

在不再需要使用new建立的对象时,可以用delete运算符予以释放。
在执行delete运算符的时候,在释放内存空间之前,会自动调用析构函数。

#include<iostream>
using namespace std;
class Box
{
 public:
    int wid;
    int len;
    int hei;
    Box(int w,int l,int h);
    ~Box();

};
Box::Box(int w,int l,int h):wid(w),len(l),hei(h)
{
    cout<<"调用构造函数"<<endl;
}
Box::~Box()
{
 cout<<"析构函数"<<endl;
}
int main()
{
 Box *p=new Box(1,2,3);

 cout<<p->wid<<" "<<p->len<<" "<<p->hei<<endl;

 delete p;
 return 0;
}

 

例题

///编写一个程序,要求先输入同学的人数,然后分别输入同学的学号、姓名和英语、数学成绩。
///然后打印出所有同学的信息
#include<iostream>
#include<string>
using namespace std;
class Student
{
private:
    int num;
    string name;
    int chinese;
    int math;
public:
    Student(int n,string m,int x,int y):num(n),name(m),chinese(x),math(y)
    {
        cout<<"调用了构造函数"<<endl;
    }

    ~Student()
    {
         cout<<"调用了析构函数"<<endl;
    }

   Student *next;
   void show()
   {
    cout<<num<<":"<<name<<"的成绩 :";
    cout<<"chinese: "<<chinese<<" , ";
    cout<<"math : "<<math<<" ";
    cout<<endl;
   }
};
int main()
{
    Student *head =NULL;
    Student *node =NULL;
    Student *p=NULL;
    int n;///n代表学生人数
    cin>>n;
    string Name;
    int C,M;
    for(int i=1;i<=n;i++)
    {
        cout<<"输入第"<<i<<"个同学的姓名,语文成绩,数学成绩"<<endl;
        cin>>Name>>C>>M;
        node=new Student(i,Name,C,M);
        if(head==NULL)
        {
            head=node;
        }
        else
        {
            p->next=node;
        }
        p=node;

        if(i==n)
            p->next=NULL;
    }

    cout<<"@@@@输出结果@@@@"<<endl;

    p=head;
    while(p!=NULL)
    {
        p->show();
        p=p->next;
    }
    ///释放对象占用的空间
    p=head;
    Student *ch;
    while(p!=NULL)
    {
        ch=p;
        p=p->next;
        delete ch;
    }

    return 0;
}

 

转载于:https://www.cnblogs.com/mcgrady_ww/p/6700385.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值