为什么每次都会出现分段错误?
问题描述:
此代码仅在运行时发生错误,它是“分段错误”。这怎么解决?我不知道如何消除这个错误。提前致谢!为什么每次都会出现分段错误?
#include <iostream>
#include <cstddef>
using namespace std;
class Node
{
private:
int data;
Node* nextNodeAddress;
public:
Node(): nextNodeAddress(NULL) {} // if next node is not used it must be null.
void setData(int); // this function sets data in the node
int retrieveData(); // this function retrieves the data from the node
};
void Node::setData(int data)
{ this->data=data; }
class List
{
private:
Node* headNode;
Node* currentNode;
int listSize;
public:
List();
void addNode(int);
void deleteNode(int);
};
List::List(): headNode(NULL),currentNode(NULL)
{
}
void List::addNode(int data)
{
Node* newNode = NULL;
newNode->setData(data);
newNode->setNextNode(NULL);
if(headNode==NULL)
headNode = newNode;
else
currentNode->setNextNode(newNode);
currentNode = newNode;
this->listSize++;
}
答
GCC与所有的警告引发此:
In member function ‘void Node::setData(int)’:
18:28: warning: declaration of ‘data’ shadows a member of 'this' [-Wshadow]
void Node::setData(int data)
可能开始检查的好地方。
编辑:这个问题进行了讨论here,基本上你在类的定义都private int
和int data
作为该方法的参数重用名称data
。 this->data = data
怎么可能决定哪一个是你的?