void 指针数组
同样,这个问题也源于“Thinking in C++”Chapter7,Q#7。我相信 Stack 头文件应该更改为 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();
};
并在 Stack.cpp 中实现 Stack::Stack(void* arr[], int size) ,我相信可能是这样的:
Stack::Stack(void* arr[], int size)
{
for (int i=0; i<size; i++)
{
push(arr[i]);
}
}
但是,在主测试文件 StackTest 中.cpp,我如何将字符串数组的地址传递给这个构造函数?这是我的想法:
#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;
}
}
但它有一些分段错误。我能想到的是将 Stack::Stack(void* arr[], int size) 更改为 Stack::Stack(string arr[], int size) ,但是它不满足问题要求。堆栈的目的是存储通用对象,例如字符串。我相信我仍然很难理解 void* 指针和指针数组的概念以及字符串数组到 void* 数组之间的变化等......任何人都可以帮我解决这个问题吗?多谢!!
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!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的 Stack 构造函数要求一个关于 stuff 的指针数组,然后你给它一个对象数组。作为奖励,我为您提供了适当的主要功能并释放内存^^
Your Stack constructor asks for an array of pointers on stuffs, and you give it an array of objects. As a bonus, I give you proper main function and freeing memory ^^