一.出现的意义:
当数组大小变化范围比较大,大小无法判定,就需要动态分配内存空间,为此c++中出现了new。(基本格式见基本用法)
而动态空间系统并不会自动回收为了防止内存被浪费掉,出现了delete。(基本格式见基本用法)
二.基本用法
1.一维数组
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int size;
cout<<"please enter the number of the sequence"<<endl;
cin>>size;
int *p=new int[size];//一维数组动态申请空间格式
for(int i=0;i<size;i++)
p[i]=i;
cout<<"the sequence is"<<endl;
for(int i=0;i<size;i++)
cout<<setw(4)<<p[i];//setw(4)是用来控制输出格式滴
cout<<endl;
cout<<"the sequence is"<<endl;
for(int i=0;i<size;i++)
cout<<setw(4)<<*(p+i);
cout<<endl;
delete[]p;//delete用法格式
return 0;
}
运行结果:
please enter the number of the sequence
5
the sequence is
0 1 2 3 4
the sequence is
0 1 2 3 4
2.二维数组
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int (*p)[3]=new int [2][3];//二维数组动态申请空间格式
int (*s)[3];
s=new int [2][3];//两种初始化方法
for(int i=0;i<2;i++)
for(int j=0;j<3;j++)
{
p[i][j]=i*j;
s[i][j]=i*j;
}
cout<<"the matrix is"<<endl;
for(int i=0;i<2;i++)
for(int j=0;j<3;j++)
cout<<setw(4)<<p[i][j];
cout<<endl;
cout<<"the another matrix is"<<endl;
for(int i=0;i<2;i++)
for(int j=0;j<3;j++)
cout<<setw(4)<<s[i][j];
delete[]p;
delete[]s;
return 0;
}
运行结果:
the matrix is
0 0 0 0 1 2
the another matrix is
0 0 0 0 1 2
三.在类中的使用,私有成员中有指针
#include<iostream>
#include<iomanip>
using namespace std;
int size=3;
class Stu
{
private:
int *p;
public:
Stu(int size)
{
p=new int[size];//申请了新空间
for(int i=0;i<size;i++)
p[i]=i;
}
void Set(int n)
{
delete p;//将上面申请的空间释放,不delete也不会有语法错误,但会消耗内存,因为动态申请空间系统不会自动回收内存
p=new int[n];
for(int i=0;i<n;i++)
p[i]=i;
}
void Show(int n)
{
for(int i=0;i<n;i++)
cout<<p[i];
}
};
int main()
{
int n=2;
Stu s(n);
s.Show(n);
cout<<endl;
n=3;
s.Set(n);
s.Show(n);
return 0;
}
运行结果:
01
012
四.主函数中的运用(易错)
#include<iostream>
#include<string>
using namespace std;
class MyClass
{
public:
void Print() const {cout<<23;}
};
int main()
{
MyClass *p=new MyClass();
(*p).Print();
return 0;
}
运行结果:
23