我正在用 C++ 实现一个链接列表。虽然我过去在 java 中做过这个,但我不明白如何在 C++ 中用指针来做这件事,因为代码可以编译,但是当我运行它时它给了我一个分段错误。我究竟做错了什么?
我的 node.h 文件
#ifndef NODE_H
#define NODE_H
#include <string>
using namespace std;
class Node
{
public:
Node(const string, const int) ;
~Node() { }
void setNext(Node *); // setter for the next variable
Node * getNext(); // getter for the next variable
string getKey(); // getter for the key variable
int getDistance(); // getter for the dist variable
private:
Node *next;
int dist;
string key;
};
#endif
我的 Node.cpp 文件
#include "node.h"
#include <string>
Node::Node(string key, int dist){
key = key;
dist = dist;
}
void Node::setNext(Node * next){
next->next;
}
Node * Node::getNext(){
return this->next;
}
string Node::getKey(){
return key;
}
int Node::getDistance(){
return dist;
}
还有我的 main.cpp 文件
#include "node.h"
#include <iostream>
using namespace std;
int main(){
Node* nptr1 = new Node("Test1", 2);
Node* nptr2 = new Node("Test2", 2);
Node* temp;
nptr1->setNext(nptr2);
temp = nptr1->getNext();
cout << temp->getKey() << "-" << temp->getDistance() << endl;
}
任何帮助将不胜感激。谢谢。