【发布时间】:2013-08-17 09:31:33
【问题描述】:
为了更好地理解该语言,我正在使用 C++ 开发一个单链表类,但我碰壁了。
遗憾的是,标题几乎是我所能想到的所有错误。 here 和 here 似乎都提出了一些我试图实施但无济于事的答案。
main.cpp:
#include <iostream>
#include <string>
#include "LinkedList.h"
#include "Node.h"
using namespace std;
int main()
{
LinkedList<string> moo2;
moo2.insertAtFront("one");
moo2.insertAtFront("two");
moo2.insertAtFront("three");
moo2.insertAtFront("four");
cout<<moo2.toString() << endl;
cin.ignore(1);
return 0;
}
LinkedList.h:
#pragma once
#include "Node.h"
#include <string>
#include <sstream>
template <class type>
class LinkedList
{
private:
int size;
node<type> *head;
public:
LinkedList()
{
head = NULL;
//head = (node<type>*)malloc(sizeof(node<type>));
size = 0;
}
/*LinkedList(const LinkedList<type> &x)
{
head = NULL;
//head = (node<U>*)malloc(sizeof(node<U>));
size = 0;
}*/
bool insertAtFront(type obj)
{
node<type> *temp;
temp = (node<type>*)malloc(sizeof(node<type>));
temp->data = obj;
temp->next = head;
head = temp;
size++;
return true;
}
std::string toString()
{
std::stringstream value;
node<type> *i = head;
while(i != NULL)
{
value << i->data;
if(i->next != NULL)
value << ", ";
i = i->next;
}
return value.str();
}
};
node.h:
#pragma once
#include <string>
template <class type>
struct node
{
type data;
node *next;
node()
{
data = NULL;
next = NULL;
//data = new type();
//next = (node<U>*)malloc(sizeof(node<U>));
}
node(type)
{
data = type;
next = NULL;
//next = (node<U>*)malloc(sizeof(node<U>));
}
node(type, node *)
{
data = type;
next = next2;
}
/*node(const node &x)
{
data = new type(x->data);
next = new x->next;
}*/
};
我不知道(无论如何可以肯定)是哪个变量造成了错误,因为它可能是 LinkedList 的 *head(或 head->data 或 head->next),也可能是节点 *next。
真正奇怪的是,对于我迄今为止尝试过的任何其他参数化类型(int、double、long、char、char*),代码都可以正常工作。事实上,我什至可以使用 char* 来实现与字符串列表相同的目标。不过,我想知道为什么我会遇到这些问题,以及可以采取什么措施来解决它。
【问题讨论】:
-
首先将
malloc替换为new(此后几乎不再使用)。 -
我希望我能将克里斯的评论提高一千次。您确实意识到 none 您的
node构造函数(以及它们的成员初始化)正在触发,对吧? -
另外,这被打破了:main24.cpp:在构造函数'node
::node(type)'中:main24.cpp:19:20:错误:预期的primary-expression before'; ' 令牌数据 = 类型; -
特别是在您评论它时混合新的 malloc,当您删除并释放数据时肯定会出错,因为您不能将 malloc 与 delete 和 new 与 free 结合使用。一旦你这样做了,你真的想在析构函数上工作,因为你分配了很多。
-
@chris 经过一些实验后,我让它适用于我测试过的所有数据类型。但是,出于好奇,您为什么说几乎不再使用其中任何一个?有没有更好的方法来实现同样的目标?
标签: c++ pointers linked-list