我正在致力于用 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;
}
如有任何帮助,我们将不胜感激。 谢谢。
最佳答案
您应该将所有成员初始化为定义的值。您不应该将参数和成员命名为相同的名称,这几乎总是会导致混淆,或者更有可能导致错误
Node::Node(string key_val, int distance)
: next(0)
{
key = key_val;
dist = distance;
}
更好的是,使用成员初始化
Node::Node(string key_val, int distance)
: next(0),
key(key_val),
dist(distance)
{
}
正如评论者已经指出的那样,您必须将 setNext()
中的 next
指针设置为给定参数,并且您应该不修改参数,但是 this->next
成员
void Node::setNext(Node * next_ptr){
next = next_ptr;
}
关于c++ - 实现链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14881809/