这里的C++问题。我已经成功(经过一些研究:P)为一个int堆栈创建了一个链表实现。我在为char *修改它时遇到了一些麻烦...
我认为这可能是与我下面定义的linklistCommands类所使用的函数有关的引用/解引用指针的问题。 (我总是很难理解何时将&或*与参数和返回值相关联。)我已经注释了代码中可能混淆的行。
无论如何,这是到目前为止的代码:
struct linkc { // one 'link', stores a pointer to a char array
char * value;
linkc *next;
};
class linklistCommands
{
public:
linklistCommands()
{top = NULL;}
~linklistCommands()
{}
void push(char * address) // Pretty sure I'm OK here.
{
linkc *temp = new linkc;
temp->value = address;
temp->next = top;
top = temp;
}
char* pop() // Pretty sure I have to change something on this line
{
if (top == NULL)
return 0;
linkc * temp;
temp = top;
char * value;
value = temp->value;
top = temp->next;
delete temp;
return value;
}
bool isEmpty()
{
if (top == NULL)
return 1;
return 0;
}
private:
linkc *top;
};
int main(void)
{
// pushed strings are of an arbitrary, but always known, length
char[4] stringA = "foo";
char[6] stringB = "fooba";
char[8] stringC = "foobar ";
linklistCommands commandList;
commandList.push(stringA);
commandList.push(stringB);
commandList.push(stringC);
while(commandList.isEmpty!=1)
{
cout << (*commandList.pop()) << endl;
}
}
感谢您阅读我的问题和/或您可以提供的任何澄清说明:)
最佳答案
您的类(class)似乎还不错,但主要内容需要更改:
// pushed strings are of an arbitrary, but always known, length
char stringA[] = "foo";
char stringB[] = "fooba";
char stringC[] = "foobar ";
linklistCommands commandList;
commandList.push(stringA);
commandList.push(stringB);
commandList.push(stringC);
while(commandList.isEmpty()!=1)
{
cout << commandList.pop() << endl;
}
您应该考虑使用std::string代替char *,它更简单,更安全。
另外,char [N] stringA =“...”;它是C#或Java语法,而不是C++
关于c++ - 从链接列表中检索字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9644826/