我有两个类,一个嵌套在另一个类中:
class List {
private:
class Node {
public:
Token data;
Node* next;
Node(const Token &dataItem, Node* nextptr);
};
Node* first;
int length;
public:
List();
virtual ~List();
void insert (const Token &t);
Node* lookup(const Token &t) const;
};
类节点有它的构造函数:
List::Node::Node(const Token &dataItem, Node* nextptr): data(dataItem) {
data = dataItem;
next = nextptr;
}
但是当我尝试在insert方法中初始化一个节点时,如下所示:
void List::insert (const Token &t){
if(first == NULL){
Node* node = new Node(t, nullptr); //PROGRAM DIES HERE
first = node;
cout<<"hey"<<endl;
}else{
Node* isHere = lookup(t);
//if not
if(isHere == NULL){
Node* temp = first;
Node* node = new Node(t, NULL);
while(true){
if((temp->data.getName().compare(t.getName())>0)or(temp->next==NULL)){
Node* temp2 = temp->next;
temp->next = node;
node->next = temp2;
break;
}
temp=temp->next;
}
}
//if node exists
else{
cout<<"node exists"<<endl;
isHere->data.newEntry(t.getLines()[0]);
cout<<"node out"<<endl;
}
}
}
查找方法:
List::Node* List::lookup(const Token &t) const{
if(first == NULL)
return first;
if(first->data.isEquivalent(t))
return first;
cout<<"finished coparre"<<endl;
Node* temp = first;
while(temp->next != NULL){
cout<<"in da loop"<<endl;
temp = temp->next;
if(temp->data.isEquivalent(t))
return temp;
}
return NULL;
}
程序只是默默地死在我评论的那一行。我在这做错了什么? 好的,这是一个令牌。我不认为那里有问题,但它也被要求了,所以这里是来源: 令牌标题:
class Token {
std::string name; // token name
int frequency;//frequency
Vector lines;//lines where the token is present
public:
//explanations for the methods in the Token.cpp
Token(std::string tokenname, int linenumber);
virtual ~Token();
void newEntry(int &linenumber);
Vector getLines() const;
std::string getName() const;
int getFrequency() const;
const bool isEquivalent(const Token &t);
令牌方法:
Token::Token(string tokenname, int linenumber) {
// TODO Auto-generated constructor stub
name = tokenname;
frequency=1;
lines.push_back(linenumber);
}
void Token::newEntry(int &linenumber){
cout<< "enter new entry"<<endl;
frequency++;
lines.push_back(linenumber);
cout<< "finish new entry"<<endl;
}
std::string Token::getName() const{
return name;
}
const bool Token::isEquivalent(const Token &t){
if(t.getName().compare(name)==0)
return true;
else
return false;
}
Vector Token::getLines() const{
return lines;
}
答案 0 :(得分:0)
构造函数中有错误:
List::Node::Node(const Token &dataItem, Node* nextptr): data(dataItem) {
data = dataItem;
next = nextptr;
}
我们还需要传递指针以使其正常工作
List::Node::Node(const Token &dataItem, Node* nextptr): data(dataItem), next(nextptr){}