[問題]C++無緣無故值被改掉

看板C_and_CPP (C/C++)作者 (JIZZUZ)時間11年前 (2014/07/08 19:22), 編輯推噓1(105)
留言6則, 3人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Dev C++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) #include <stdio.h> #include <iostream> 問題(Question): 這是一個很簡單的用Node class連起來的Linklist class Node裡的private data就是 一個int 一個char 一個指向下一Node的pointer 一個指向上一個Node的pointer 但一件很陰的事情發生了 各位大大請先看主程式 我Call了 b.locate(4) 竟然會改到head Node的int值? 我甚至locate都刪到只剩一行cout還是被改 有哪位高手能解決我的問題嗎 餵入的資料(Input): 預期的正確結果(Expected Output): 1 c 1 1 c 錯誤結果(Wrong Output): 1 c 4 4 c 程式碼(Code):(請善用置底文網頁, 記得排版) class Node{ public: int readi() const; char readc() const; Node* readn() const; Node(); Node(int i,char c); private: int datai; char datac; Node *prior,*next; }; int Node::readi() const{ return datai; } char Node::readc() const{ return datac; } Node* Node::readn() const{ return next; } Node::Node(int in,char c){ datai=in; datac=c; prior=NULL; next=NULL; } class Linklist{ public: Linklist(); Linklist(Node h); void locate(int i); void Show(); private: Node *head; }; Linklist::Linklist(Node h){ head=&h; } void Linklist::Show(){ Node *temp; if(head!=NULL){ temp=head; } else{ cout<<"list has nothing\n"; } while(1){ cout<<temp->readi()<<" "<<temp->readc()<<endl; if(temp->readn()==NULL)break; else temp=temp->readn(); } } void Linklist::locate(int i){ cout<<head->readi()<<endl; } int main(){ Node a(1,'c'); Linklist b(a); b.Show(); b.locate(4); b.Show(); } 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.229.67.67 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1404818573.A.E56.html

07/08 19:32, , 1F
在 Linklist ctor 中, head 存的是函式 argument 的位址
07/08 19:32, 1F

07/08 19:32, , 2F
這在 ctor 結束之後就會失效
07/08 19:32, 2F

07/08 19:33, , 3F
你把參數型態改成 Node & 試試
07/08 19:33, 3F

07/08 19:42, , 4F
太太....太神啦!!!!!!CaptainH謝謝啦!成功了
07/08 19:42, 4F

07/08 20:04, , 5F
下次遇到這種「不知道誰改我」的問題
07/08 20:04, 5F

07/08 20:04, , 6F
可以試著用 gdb 下一隻 watch dog
07/08 20:04, 6F
文章代碼(AID): #1JkzIDvM (C_and_CPP)
文章代碼(AID): #1JkzIDvM (C_and_CPP)