#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;
} ///:~