第六章的牛叉程序

#ifndef STASH2_H///头文件
#define STASH2_H
class Stash {
  int size;      // 类型的大小
  int quantity;  // 此时的可用空间量非字节
  int next;      // 下一个空间

  unsigned char* storage;unsigned char 是一字节的
  void inflate(int increase);///重新申请内存
public:
  Stash(int size);///构造函数
  ~Stash();
  int add(void* element);
  void* fetch(int index);
  int count();
};
#endif // STASH2_H ///:~
//
//: C06:Stash2.cpp {O}
#include "Stash2.h"
#include "../require.h"
#include <iostream>
#include <cassert>
using namespace std;
const int increment = 100;

Stash::Stash(int sz) {
  size = sz;
  quantity = 0;
  storage = 0;
  next = 0;
}

int Stash::add(void* element) {
  if(next >= quantity) // 不够空间了
    inflate(increment);//重新分配

  int startBytes = next * size;
  unsigned char* e = (unsigned char*)element;//强制转换为一字节的指针
  for(int i = 0; i < size; i++)
    storage[startBytes + i] = e[i];//字节级别的赋值
  next++;
  return(next - 1); // Index number
}

void* Stash::fetch(int index) {
  require(0 <= index, "Stash::fetch (-)index");
  if(index >= next)
    return 0; // 
  return &(storage[index * size]);//返回第n个数据的地址
}

int Stash::count() {
  return next; // N
}

void Stash::inflate(int increase) {
  require(increase > 0, 
    "Stash::inflate zero or negative increase");
  int newQuantity = quantity + increase;//新空间量
  int newBytes = newQuantity * size;//新空间量的总字节量
  int oldBytes = quantity * size;/旧空间量的总字节量

  unsigned char* b = new unsigned char[newBytes];分配新空间
  for(int i = 0; i < oldBytes; i++)
    b[i] = storage[i]; //字节级别的赋值
  delete [](storage); 释放久空间
  storage = b; //指向新的空间
  quantity = newQuantity;
}

Stash::~Stash() {
  if(storage != 0) {/如果storage为0,则不释放了
   cout << "freeing storage" << endl;
   delete []storage;
  }
} ///:~
//
///: C06:Stash2Test.cpp
//{L} Stash2
#include "Stash2.h"
#include "../require.h"
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main() {
  Stash intStash(sizeof(int));//初始化为int类型量

  for(int i = 0; i < 100; i++)
    intStash.add(&i);
  for(int j = 0; j < intStash.count(); j++)
    cout << "intStash.fetch(" << j << ") = "
         << *(int*)intStash.fetch(j)//强制转换回来才可以解引用
         << endl;

  const int bufsize = 80;
  Stash stringStash(sizeof(char) * bufsize);//我擦!
  ifstream in("Stash2Test.cpp");
  assure(in, " Stash2Test.cpp");
  string line;
  while(getline(in, line))
    stringStash.add((char*)line.c_str());
  int k = 0;
  char* cp;
  while((cp = (char*)stringStash.fetch(k++))!=0)
    cout << "stringStash.fetch(" << k << ") = "
         << cp << endl;
} ///:~














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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

紫云的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值