この質問は、「Thinking in C ++」Vol-1、第5章の演習No.14からのものです。
StackImpと呼ばれるクラスに要素を格納するために使用する低レベルのデータ構造を非表示にする「Cheshirecat」手法を使用して、StackOfIntクラス(intを保持するスタック)を作成します。StackImpの2つのバージョンを実装します。1つはintの固定長配列を使用し、もう1つはベクトルを使用します。スタックの最大サイズを事前に設定しておくと、最初のバージョンでアレイを拡張することを心配する必要がなくなります。StackOfInt.hクラスはStackImpで変更する必要がないことに注意してください。
これが私が作成したヘッダーファイル(StackOfInt.h
)です:
#ifndef STACKOFINT_H
#define STACKOFINT_H
class StackOfInt
{
int size;
int curr_idx;
class StackImp;
StackImp* head;
public:
void initialize(int max);
void push(void* dat);
void* peek();
void* pop();
void cleanup();
};
#endif
ただし、実装に関しては、配列とベクトルの違いを処理する方法について混乱しています。これが私がこれまでに思いついたものです:
#include "StackOfInt.h"
#include "require.h"
#include <vector>
class StackOfInt::StackImp
{
int arrInt[50];
public:
void initialize()
{
for (int i = 0; i < 50; i++)
{
arrInt[i] = 0;
}
}
};
/*
class StackOfInt::StackImp
{
std::vector<int> vecInt;
}
*/
void StackOfInt::initialize(int max)
{
size = max;
curr_idx = 0;
head = 0;
StackImp* newImp = new StackImp;
newImp->initialize();
}
void StackOfInt::push(void* dat)
{
*(head+curr_idx) = dat;
curr_idx++;
}
void* Stack::peek(int idx)
{
require(head != 0, "Stack empty");
return head[idx];
}
void Stack::cleanup()
{
require(head == 0, "Stack not empty");
} ///:~
私は間違った方向に進んでいると思いますが、誰かがこの問題を解決する方法についていくつかのヒントを教えてもらえますか?