[问题]C++无缘无故值被改掉

楼主: jizzman (JIZZUZ)   2014-07-08 19:22:50
开发平台(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):
作者: CaptainH (Cannon)   2014-07-08 19:32:00
在 Linklist ctor 中, head 存的是函式 argument 的位址这在 ctor 结束之后就会失效你把参数型态改成 Node & 试试
楼主: jizzman (JIZZUZ)   2014-07-08 19:42:00
太太....太神啦!!!!!!CaptainH谢谢啦!成功了
作者: yoco315 (眠月)   2014-07-08 20:04:00
下次遇到这种“不知道谁改我”的问题可以试着用 gdb 下一只 watch dog

Links booklink

Contact Us: admin [ a t ] ucptt.com