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