new和delete

new 和 delete 深层次用法

String类

class String
{
private:
    char * str;             // 指向字符串的指针
    int len;                // 字符串长度
    static int num_strings; // String类对象个数
    static const int CINLIM = 80;  // 每个String对象限制输入的字符
public:
// 构造函数和析构函数
    String(const char * s); // 构造函数
    String();               // 默认构造函数
    String(const String &); // 复制构造函数
    ~String();              // 析构函数
    int length () const { return len; }        //字符串长度


// 运算符重载函数    
    String & operator=(const String &);
    String & operator=(const char *);
    char & operator[](int i);
    const char & operator[](int i) const;


// 友元函数
    friend bool operator<(const String &st, const String &st2);
    friend bool operator>(const String &st1, const String &st2);
    friend bool operator==(const String &st, const String &st2);
    friend ostream & operator<<(ostream & os, const String & st);
    friend istream & operator>>(istream & is, String & st);


// 静态方法
    static int HowMany();
};


String sayings[5];
String * favorite =  new String(sayings[choice]);		// choice取随机值

这一段就是说给一个String的对象sayings[choice]分配内存,通复制构造函数来初始化一个无名对象,这个对象使用指针favorite来管理.

首先,new只是为这个对象分配内存,也就是说只给str和len分配了内存,其中静态变量是在另一个内存区,也不是为new分配的.str是字符指针类型,仅仅只给这个地址类型分配过空间,并没有为str所指字符串空间分配空间.str指向的字符串应当是通过构造函数来申请的空间.

如果不想要这个对象,那么就

delete favorite;

调用delete的时候就是将favorite的空间删掉,其中包括str指针(仅仅是str这个指针类型所占有的空间,并没有通过delete删除str所指空间)和len变量的空间,静态变量在程序结束的时候自动销毁.在调用delete之后,将会调用*favorite的析构函数来释放str所指空间.示意图如下

在这里插入图片描述

而且一定要注意的是,对象如果是new出来的,只有执行delete,才会执行析构函数.

指针和对象

String * glamour;		// 声名指向类的指针,一个野指针,并没有干任何事情

String * first = &saying[0];		// saying[0]是一个String已经存在的对象,first指向一个已经存在的对象

String * favorite =  new String(sayings[choice]);
// choice是一个随机值	
// favorite指向一个通过String(const String&)复制构造函数创造一个无名对象

String * gleep =new String;		// 通过使用默认的构造函数进行初始化,通过gleep管理


String * glop = new String("my my my");		// 通过使用String(const char *)类的构造函数构造出一个无名对象,用glop指针进行管理

glop->length()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值