1 回答

TA貢獻1886條經驗 獲得超2個贊
1.CWnode沒有構造函數,導致新生成的CWnode結點的link成員不是空,而是隨機指向某個地址,導致錯誤.
2.自己寫類時,永遠不要在某個函數中直接返回類對象,正確的方法是要么使用引用,要么返回指針.
3.Length函數里,for循環的第三個部分寫錯了.
正確代碼如下:
#include<iostream.h>
class CWnodeChain;
class CWnode
{
friend CWnodeChain;
private:
int data;
CWnode *link;
public: //加上默認構造函數
CWnode():link(0){};
};
class CWnodeChain
{
public:
CWnodeChain(){first=0;}
~CWnodeChain();
int Length();
CWnodeChain &Insert(int nd); //返回類型用引用
void Output();
private:
CWnode *first;
};
CWnodeChain::~CWnodeChain()
{
CWnode *p=first;
while(first)
{
p=first->link;
delete first;
first=p;
}
}
int CWnodeChain::Length()
{
CWnode *p;
int len=0;
for(p=first;p;p=p->link) //原來你寫的是p->link
{
len++;
}
return len;
}
CWnodeChain &CWnodeChain::Insert(int nd) //返回類型是引用
{
CWnode *q=new CWnode;
q->data=nd;
//從頭接點插入
if(!first)
{
first=q;
}
else
{
q->link=first;
first=q;
}
return *this;
}
void CWnodeChain::Output() //輸出
{
CWnode *p;
for(p=first;p;p=p->link)
cout<<p->data<<endl;
}
void main()
{
CWnodeChain obj;
cout<<obj.Length()<<endl;
obj.Insert(3);
cout<<obj.Length()<<endl;
obj.Output();
}
- 1 回答
- 0 關注
- 185 瀏覽
添加回答
舉報