0
我剛剛開始使用C++。我試圖用C++編寫一個簡單的LinkedList。 但是我收到以下錯誤,因爲我無法弄清楚爲什麼我無法使用鏈接對象*newLinkThree
調用成員函數printAll
。LinkedList實現C++錯誤指針間接尋址
main.cpp:40:16: error: member reference type 'Link *' is a pointer; maybe you
meant to use '->'?
*newLinkThree.printAll(newLinkThree);
~~~~~~~~~~~~^
->
main.cpp:40:3: error: indirection requires pointer operand ('void' invalid)
*newLinkThree.printAll(newLinkThree);
這是我的代碼 -
#include <iostream>
using namespace std;
class Link {
char* value;
Link* next;
public:
Link(char* val, Link* nextLink) {
value = val;
nextLink = next;
}
~Link() {
value = NULL;
delete[] next;
}
void printAll(Link* top) {
if(top->next == NULL) {
cout<<top->value<<endl;
return;
}
cout<<top->value<<endl;
printAll(top->next);
}
};
int main() {
char* first = "First";
char* second = "Second";
char* third = "Third";
Link* newLink = new Link(first, NULL);
Link* newLinkTwo = new Link(second, newLink);
Link* newLinkThree = new Link(third, newLinkTwo);
*newLinkThree.printAll(newLinkThree);
return 0;
}
謝謝!我的printAll不是打印所有的三個值。由於某種原因,它僅印刷第三張。你能幫我解決嗎? – Kek
@Kek呃,那是另一個問題。但在提出新問題之前,我建議您嘗試調試並找出具體問題。如果仍然無法解決問題,請再次提出一個新問題。 – songyuanyao
@Kek一些問題:'nextLink = next;'應該是'next = nextLink;',在構造函數中。 delete []'應該是析構函數中的'delete'。 – songyuanyao