again this question is also origined from "Thinking in C++" Chapter7, Q#7. I believe the Stack header file should be changed to Stack.h
#ifndef STACK_H
#define STACK_H
class Stack {
struct Link {
void* data;
Link* next;
Link(void* dat, Link* nxt);
~Link();
}* head;
public:
Stack();
Stack(void* arr[], int size);
~Stack();
void push(void* dat);
void* peek();
void* pop();
};
and the implementation of Stack::Stack(void* arr[], int size) in Stack.cpp, I believe could be like:
Stack::Stack(void* arr[], int size)
{
for (int i=0; i<size; i++)
{
push(arr[i]);
}
}
However, in the main test file StackTest.cpp, how could I pass the address of a string array to this constructor? Here is what I come up with:
#include "Stack.h"
#include "require.h"
#include <iostream>
#include <string>
using namespace std;
int main() {
string tst_arr[] = {"hi 1", "hi 2", "hi 3"};
Stack string_arr((void**)tst_arr, 3);
string* s;
while((s = (string*)string_arr.pop()) != 0) {
cout << *s << endl;
delete s;
}
}
But it has some segmentation fault. What I could think of is to change Stack::Stack(void* arr[], int size) to Stack::Stack(string arr[], int size), however it doesn't satisfies the question requirement. The purpose of Stack to store generic objects, including string for example. I believe I still have difficulty to understand the conceipt of void* pointer and array of pointers and the chagne between string array to void* array etc... Anyone could help me solve this problem? Thanks a lot!!