菜鸟问stash with constructors

stupidfish2004 2004-10-24 09:38:30
thinking in c++ 第六章里面的例子,看得一头雾水,请高手讲解一下!

.h文件略去
.cpp文件如下:
#include "Stash2.h"
#include "G:\C++\mylibary\yuanma\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;//(unsigned char*)element打个括号是什么意思?究竟把什么值赋给了char*e?
for(int i = 0; i < size; i++)
storage[startBytes + i] = e[i];//上面不是定义的unsigned char*e吗,怎么出来数组e[i了?
next++;
return(next - 1);
}

void* Stash::fetch(int index) {
require(0 <= index, "Stash::fetch (-)index");//require 是做什么用得?
if(index >= next)
return 0; // To indicate the end
// Produce pointer to desired element:
return &(storage[index * size]);
}

int Stash::count() {
return next; // Number of elements in CStash
}

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]; // Copy old to new
delete [](storage); // Old storage
storage = b; // Point to new memory
quantity = newQuantity;
}

Stash::~Stash() {
if(storage != 0) {
cout << "freeing storage" << endl;
delete []storage;
}
} ///:~



主函数如下:
int main() {
Stash intStash(sizeof(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)//*(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;
}
感觉主函数完全看不懂,郁闷啊,请高手帮忙讲解一下把!谢谢
...全文
41 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

64,662

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧