gpt4 book ai didi

c++ - 无法初始化内部类 C++ 的对象

转载 作者:太空宇宙 更新时间:2023-11-04 13:33:05 25 4
gpt4 key购买 nike

我有 2 个类,一个嵌套在另一个类中:

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;
}

但是当我尝试在插入方法中初始化其中一个节点时,如下所示:

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;
}

程序在我评论的那一行默默地死掉了。我在这里做错了什么?好的,这是一个 token 。我不认为那里有问题,但也有人要求,所以这里是来源: token header :

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::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;
}

最佳答案

构造函数出错:

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){}

关于c++ - 无法初始化内部类 C++ 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30722633/

25 4 0
文章推荐: jquery - 使
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com