2

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!!

4

1 回答 1

2

你的 Stack 构造函数请求一个关于东西的指针数组,然后你给它一个对象数组。作为奖励,我给你适当的主要功能和释放内存^^

#include <cstdlib>
// --- Includes your stuffs ---

using namespace std;

int main(int argc, char* argv[]) {
  string* tst_arr[] = new string[3];
  tst_arr[0] = new string("hi 1");
  tst_arr[1] = new string("hi 2");
  tst_arr[2] = new string("hi 3");
  Stack string_arr((void**)tst_arr, 3);

  // --- Do your stuffs ---

  for(int i =0; i < 3; ++i)
    delete tst_arr[i];
  delete[] tst_arr;

  return EXIT_SUCCESS;
}
于 2011-03-30T00:59:56.540 回答