對於一個學校項目,我試圖在同一時間製作二叉搜索樹,我們應該學習如何在課堂中使用「友誼」。我在編譯時遇到的錯誤是:[我將代碼中的註釋放在錯誤源於清楚的代碼中](請記住,我不允許在BST類中嵌套Node,它們都應該在單獨的文件和類中這種編程任務的緣故)爲二叉搜索樹創建一個新節點
BST.cpp: In member function `void BST::insert(std::string, std::string)':
BST.cpp:51: error: non-lvalue in assignment
BST.cpp:58: error: non-lvalue in assignment
BST.cpp:62: error: non-lvalue in assignment
makefile.txt:9: recipe for target `BST.o' failed
make: *** [BST.o] Error 1
我試着用在BST.cpp和Node.cpp「新」經營者,但我仍然無法擺脫那些錯誤信息。我相信我可能會錯過一些使編譯器不喜歡它的語法。以下是此任務所用的文件:(的arent尚未使用注意一些功能,因爲我還沒有得到那麼遠的項目。) Node.h
#ifndef NODE_H_INCLUDED
#define NODE_H_INCLUDED
#include <iostream>
#include <string>
using namespace std;
class BST;
class Node
{
public:
Node(string key, string data)
{m_key = key; m_data = data;}
~Node();
static string get_key(); //takes in ptr to node and returns its key
static string get_data(); //takes in ptr to node and returns its data
static Node* get_left(); //takes in ptr to node and returns its left child pointer
static Node* get_right(); //takes in ptr to node and returns its right child pointer
static Node* get_parent(); //takjes in ptr to node and returns its parent pointer
static Node* create_node(string key, string data);
static void destroy_node();
private:
string m_key;
string m_data;
Node *m_left;
Node *m_right;
Node *m_parent;
};
#endif // NODE_H_INCLUDED
Node.cpp
#include "Node.h"
static string Node::get_key()
{
return m_key;
}
static string Node::get_data()
{
return m_data;
}
static Node* Node::get_left()
{
return m_left;
}
static Node* Node::get_right()
{
return m_right;
}
static Node* Node::get_parent()
{
return m_parent;
}
static Node* Node::create_node(string key, string data)
{
Node* ptr = new Node(key, data);
ptr->m_left = NULL;
ptr->m_right = NULL;
ptr->m_parent = NULL;
return ptr;
}
我到目前爲止,意圖是讓Node :: create_Node創建一個新節點,取消所有指針,最後將節點的指針傳遞迴BST.cpp,這樣指針可以被修改並插入到樹中。下面是BST.cpp和BST.h(我放到哪裏你清晰出現的錯誤評論) BST.h:
#ifndef BST_H_INCLUDED
#define BST_H_INCLUDED
#include <iostream>
#include <string>
using namespace std;
class BST
{
public:
BST()
{m_root = NULL;}
~BST();
void insert(string key, string data);
void find(string key);
void remove(string key, string data);
void print();
friend class Node;
private:
Node* m_root;
};
#endif // BST_H_INCLUDED
最後,BST.cpp(其中發生的錯誤)當我嘗試的錯誤發生修改z的指針(z是指向剛創建的全新節點的指針),包括它的m_left,m_right和m_parent。
#include "BST.h"
#include "Node.h"
void BST::insert(string key, string data)
{
Node* x = m_root;
Node* y = NULL;
Node* z = Node::create_node(key, data);
while(x != NULL)
{
y = x;
if(key < x->get_key())
{
x = x->get_left();
}
else
{
x = x->get_right();
}
}
z->get_parent() = y; //error: non-lvalue in assignment
if(y == NULL)
{
m_root = z;
}
else if(z->get_key() < y->get_key())
{
y->get_left() = z; //error: non-lvalue in assignment
}
else
{
y->get_right() = z; //error: non-lvalue in assignment
}
}
getter的結果不是左值,您不能爲其分配新的值。相反,您希望將其分配給m_left字段本身。 – flup
getter函數不應該是靜態的,它們不能訪問對象,因爲賦值問題我會實現setter函數並使用那些 – Sigroad