我正在嘗試在 C 中實作一個鏈表,并嘗試使用“[]”來合并像資料訪問這樣的陣列。
首先,我宣告了一個 Node 類,如下所示。
class Node{
public:
int data;
Node *next, *prev;
Node(int val){
this -> data = val;
this -> next = NULL;
this -> prev = NULL;
}
};
然后我實作了 Linkedlist 類,如下所示,我多載了 '[]' 運算子,如下所示
class LinkedList{
public:
Node *head;
LinkedList(){
this -> head = NULL;
}
LinkedList(Node *h){
this -> head = h;
}
int operator [] (int index){
if(index < 0 || index >= getsize(this -> head)){
cout << "List out of bounds" << endl;
return -1;
}else{
Node *cur = this -> getnode(index);
return cur -> data;
}
}
Node* getnode(int index){
int count = 0;
Node *cur = this -> head;
while(cur != NULL){
if(count == index)
break;
count ;
cur = cur -> next;
}
return cur;
}
};
在主要功能中,我嘗試列印'l [0]'。它顯示錯誤為
no operator "<<" matches these operandsC/C (349)
linklist_sort.cpp(173, 10): operand types are: std::ostream << LinkedList
請幫幫我。我在這里錯過了一些概念嗎?
主要功能:
int main(){
srand(time(0));
LinkedList *l = new LinkedList();
for(int i = 0; i<10; i ){
int num = rand() % 50 1;
l -> head = l -> insert(l->head,num);
}
l->printlist(l->head);
int n1, n2;
cout << "\n";
cin >> n1 >> n2;
l->swap(l->head,n1,n2);
l->printlist(l->head);
cout << "\n";
cout << l[0]; //Error here
return 0;
}
getsize 函式:
int getsize(Node *head){
if(head == NULL)
return 0;
else
return 1 getsize(head->next);
}
uj5u.com熱心網友回復:
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/423983.html
