王老师 C++ 运算符重载 转换函数 第三讲

<敲了半天,没提交上,郁闷,不重写了> 

示例程序:

(1)new

#include <stdafx.h>
#include <malloc.h>
#include <iostream>
using namespace std;

class com
{
public:
 int real, image;

 com(int x, int y)
 {
  this->real = x;
  this->image = y;
 }
};

void main()

{

com c(2, 3);

com *p, *q;

//在堆中分配空间
p = new com(2, 4);

//这两种方式都能动态创建一个对象
//但是下面的语句内存没有初始化
q = (com *)malloc(sizeof(com));
q->real = 2;
q->image = 4;
cout << "hehe" << endl;

//error C2512: 'com' : no appropriate default constructor available
new com[3];

}

(2)重载new delete

示例:在静态区申请动态对象

#include <stdafx.h>
#include <iostream>
using namespace std;

#define N 3

class Item
{
 int info, mark;

public:

 static Item static_Zone[N];

 Item()
 {
  cout << this << endl;
  mark = 0;
 }

 Item(int x)
 {
  this->info = x;
  this->mark = 1;
 }

 ~Item()
 {
  cout << "deconstructor is called!" << endl;
  this->mark = 0;
 }

 void * operator new(size_t size) throw (int)
 {
  cout << "my new" << endl;
  for(int i = 0; i < N; i++)
  {
   if(static_Zone[i].mark == 0)
   {
    cout << &static_Zone[i] << endl;
    return &static_Zone[i];
   }
  }
  throw 1;
 }

 void operator delete(void *p)
 {
  cout << "my delete" << endl;
  if(p == NULL)
   return ;
  ((Item *)p)->mark = 0;
 }
};

Item Item::static_Zone[N];

void functiona()
{
 Item *p, *q, *r, *s;
 try
 {
  p = new Item(3);
  q = new Item(4);
  r = new Item(5);
  s = new Item(6);  
 }catch(int)
 {
  cout << "memory leak!" << endl;
  delete p;
  s = new Item(6);
 }
}

(3)析构函数和delete的区别

析构函数负责释放由构造函数申请的内存.

delete负责释放new动态申请的内存.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值