c++中的new和delete

 

一.出现的意义:

当数组大小变化范围比较大,大小无法判定,就需要动态分配内存空间,为此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

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值