C++對象的動態(tài)建立與釋放詳解
=============下面先給出一個new和delete基本應用的例子,回顧一下它的基本用法============
#include<iostream>
using namespace std;
int main()
{
int *p;//定義一個指向int型變量的指針p
p=new int(3);//開辟一個存放整數(shù)的存儲空間,返回一個指向該存儲空間的的地址
cout<<*p<<endl;
delete p;//釋放該空間
char *p_c;
p_c=new char[10];//開辟一個存放字符數(shù)組(包括10個元素)的空間,返回首元素的地址
int i;
for(i=0;i<10;i++)
{
*(p_c+i)=i+'0';
}
for(i=0;i<10;i++)
{
cout<<*(p_c+i);
}
delete [] p_c;
cout<<endl;
return 0;
}
運行結果:

同樣的,new和delete運算符也可以應用于類的動態(tài)建立和刪除
用new運算符動態(tài)地分配內存后,將返回一個指向新對象的指針的值,即所分配的內存空間的起始地址。用戶可以獲得這個地址,并用這個地址來訪問對象。
當然C++還允許在執(zhí)行new時,對新建的對象進行初始化。
Box *pt =new Box(12,15,18);
用new建立的動態(tài)對象一般是不用對象名的,而是通過指針進行訪問,它主要應用于動態(tài)的數(shù)據(jù)結構,如鏈表等。訪問鏈表中的結點,并不需要通過對象名,而是在上一個結點中存放下一個節(jié)點的地址,從而用上一個結點找到下一個結點,構成連接關系。
在不再需要使用new建立的對象時,,可以用delete運算符予以釋放。在執(zhí)行delete運算符的時候,在釋放內存空間之前,會自動調用析構函數(shù)。
#include<iostream>
using namespace std;
class Box
{
public:
Box(int w,int l,int h);
~Box();
int width;
int length;
int height;
};
Box::Box(int w,int l,int h)
{
width=w;
length=l;
height=h;
cout<<"========調用構造函數(shù)=======\n";
}
Box::~Box()
{
cout<<"========調用析構函數(shù)=======\n";
}
int main()
{
Box * p=new Box(12,13,15);
cout<<"\n輸出指針指向的對象的數(shù)據(jù)成員"<<endl;
cout<<p->width<<"\t"<<p->length<<"\t"<<p->height<<endl;
delete p;
return 0;
}

然后,舉一個更加實際的例子
=========================題目=======================
編寫一個程序,要求先輸入同學的人數(shù),然后分別輸入同學的學號、姓名和英語、數(shù)學成績。
然后打印出所有同學的信息
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
class Student
{
public:
Student(int num, string nam, float e,float m);
void show();
Student * next;
private:
int number;
string name;
float English;
float Math;
};
Student::Student(int num,string nam,float e,float m)
{
number=num;
name=nam;
English=e;
Math=m;
}
void Student::show()
{
cout<<setiosflags(ios::left);
cout<<setw(10)<<number;
cout<<setw(15)<<name;
cout<<"English:"<<setw(10)<<English;
cout<<"Math:"<<setw(10)<<Math;
cout<<endl;
}
int main()
{
int i=0,n;
cout<<"請輸入同學人數(shù):";
cin>>n;
Student * head=NULL;
Student * node=NULL;
Student * p=NULL;
string name;
float English;
float Math;
for(i=1;i<=n;i++)
{
cout<<"請輸入第"<<i<<"個同學的姓名,英語成績,數(shù)學成績"<<endl;
cin>>name>>English>>Math;
node=new Student(i,name,English,Math);
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 * l;
while(p!=NULL)
{
l=p;
p=p->next;
delete l;
}
return 0;
}
運行結果:

相關文章
C語言不使用strcpy函數(shù)如何實現(xiàn)字符串復制功能
這篇文章主要給大家介紹了關于C語言不使用strcpy函數(shù)如何實現(xiàn)字符串復制功能的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-02-02