[英]Error: 'object' was not declared in this scope (C++)
我正在嘗試編寫Node
對象的鏈接列表,其中每個Node
包含:字符串data
和指針next
。 為了管理列表(例如:添加/刪除節點),我有Node
對象: head
, curr
和temp
。 我正在嘗試找出將新數據添加到列表時如何將每個節點鏈接到上一個節點,但是這樣做很麻煩。 當我嘗試將新節點n
鏈接到curr
節點的next
指針時,在Node.cpp中發生了錯誤。
LinkedList.cpp:
#include <iostream>
#include <cstdlib>
#include "LinkedList.h"
#include "Node.h"
using namespace std;
LinkedList::LinkedList(value_type setData) {
head.setData(setData);
cout << head.getData() << endl;
}
void LinkedList::addNode(value_type addData) {
Node n;
n.setData(addData);
if (head.getData() != "") {
curr = head;
while(curr.getNext() != NULL) {
//Still writing this..
}
curr.setNext(n); //Is this correct?
}
else {
head = n;
}
}
LinkedList.h:
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include "Node.h"
class LinkedList {
public:
typedef std::string value_type;
LinkedList();
LinkedList(value_type setData);
void addNode(value_type addData);
private:
Node head;
Node curr;
Node temp;
};
#endif
Node.cpp:
#include <iostream>
#include <cstdlib>
#include "Node.h"
using namespace std;
Node::Node() {
data = "";
next = NULL;
}
void Node::setData(value_type setData) {
data = setData;
}
string Node::getData() {
return data;
}
void setNext(Node n) {
next = n; //'next' was not declared in this scope error.
//Does this assignment statement even work in this scenario?
}
Node * Node::getNext() {
return next;
}
Node.h:
#ifndef NODE_H
#define NODE_H
class Node {
private:
typedef std::string value_type;
value_type data;
Node* next;
public:
Node();
void setData(value_type setData);
value_type getData();
void setNext(Node n);
Node * getNext();
};
#endif
謝謝大家的任何幫助。
你有這行:
void setNext(Node n) {
您可能想要這樣:
void Node::setNext(Node n) {
函數void setNext(Node n);
在class Node
聲明。 因此,在Node.cpp
,必須使用void Node::setNext(Node n);
定義函數void Node::setNext(Node n);
。 符號::
將顯示函數的范圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.