怎么看星月菩提的好坏:帮我看看问题出在哪儿(C++)

来源:百度文库 编辑:查人人中国名人网 时间:2024/04/30 06:46:18
#include <iostream>
using namespace std;

class Node
{
public:
Node(char* name){itsName=name;}
~Node(){delete itsName;itsName=0;}
char* GetName() const {return itsName;}
Node & operator=(Node &);
void SetName(char* name) {itsName=name;}
private:
char* itsName;
};

Node & Node::operator=(Node &rhs)
{
itsName=rhs.GetName();
return *this;
}

int main()
{
int choice;
char pName[10];
Node oldNode=0;
cout<<"Name: ";
cin>>pName;

oldNode.SetName(pName);

while(1)
{
re: cout<<"(0).exit (1)do"<<endl;
cout<<"CHOOSE: ";
cin>>choice;

if(choice==0)
break;
if(choice==1)
{

cout<<"NewName: ";
cin>>pName;

cout<<"old is: "<<oldNode.GetName()<<endl;//为什么cin>>pName后,oldNode里面的东西会改变?

Node* pNode=new Node(pName);
oldNode=*pNode;

cout<<"new is: "<<pNode->GetName()<<endl;
}
else
goto re;
}
return 0;
}

为什么cin>>pName后,oldNode里面的东西就会改变,而不是在oldNode=*pNode;之后?

问题在这里:
oldNode.SetName(pName);
调用 Node 成员函数 void SetName(char* name) {itsName=name;}
相当于oldNode.itsName=pName 指针也就指向了 pName;
因此pName变时,oldNode.itsName(其实指向就是pName)也就变了

要改正:
首先把itsName从指针改为字符数组
把SetName函数中用strcpy()改写。就可以了