[問題] Linked List 與operator overloading []
遇到的問題:無法跑出所希望的結果
希望得到的正確結果:希望能以類似陣列的方式使用linked list
程式跑出來的錯誤結果:程式不會跑進我寫的operator []
開發平台:VC++ 2008 (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux)
有問題的code:有點多@@希望不會太亂 (請善用置底文標色功能)
node.h
class node
{
public:
node();
node(int c,int e);
friend class polynomial;
node& operator [] (int index);
private:
int coef;//資料1
int exp;//資料2
node* link;//鏈
};
node.cpp
#include"node.h"
#include<iostream>
node::node()//可忽略
{
coef=0;
exp=0;
link=NULL;
}
node::node(int c, int e)//可忽略
{
coef=c;
exp=e;
link=NULL;
}
node& node::operator [](int index)
{
node* temp=this;
for(int i=0;i<index;i++)
{
temp=temp->link;
}
return *temp;
}
polynomial.h
#include"node.h"
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
class polynomial
{
public:
polynomial();
void insert(int c,int e);//新增
void show();//顯示結果
private:
int n;//多項式項數
node* first;//鏈的開頭
};
#endif
polynomial.cpp
#include"polynomial.h"
#include<iostream>
using std::cout;
using std::endl;
polynomial::polynomial()//可忽略
{
node();
n=0;
first=NULL;
}
void polynomial::insert(int c, int e)
{
if(!n)//當鏈結空時
{
first=new node(c,e);
n++;
}
else//以下是希望能用類似陣列方式使用的地方
{
for(int i=0;i<n;i++)
{
if(e>first[i].exp)//新增指數大於當前者則放在前面
{
if(i==0)//如果剛好是第一個
{
node* temp=first;
first=new node(c,e);
first->link=temp;
n++;
break;
}
else
{
node* temp=first[i-1].link;
first[i-1].link=new node(c,e);
first[i-1].link=temp;
n++;
break;
}
}
else if(e==first[i].exp)//指數相等直接相加
{
first[i].coef+=c;
break;
}
else if(i==(n-1))//新增者為最小則擺最後
{
first[i].link=new node(c,e);
n++;
break;
}
}
}
}
void polynomial::show()//這裡也是想用類似陣列方式的地方
{
for(int i=0;i<n;i++)
{
cout<<first[i].coef<<"x^"<<first[i].exp<<" ";
}
cout<<endl;
}
main.cpp//只是一般的測試@@可忽略
#include"polynomial.h"
int main()
{
polynomial p1;
p1.insert(2,2);
p1.insert(3,3);
p1.insert(1,2);
p1.insert(1,1);
p1.insert(3,5);
p1.show();
return 0;
}
補充說明:
compiler雖然會過
但是用逐步執行時發現程式根本沒有跑到我寫的oeprator [] 過
為什麼呢???
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.132.50.53
※ 編輯: stupid2 來自: 220.132.50.53 (10/31 16:30)
→
10/31 16:31, , 1F
10/31 16:31, 1F
→
10/31 16:32, , 2F
10/31 16:32, 2F
→
10/31 16:33, , 3F
10/31 16:33, 3F
→
10/31 16:39, , 4F
10/31 16:39, 4F
→
10/31 16:39, , 5F
10/31 16:39, 5F
→
10/31 16:43, , 6F
10/31 16:43, 6F
→
10/31 16:44, , 7F
10/31 16:44, 7F
→
10/31 16:44, , 8F
10/31 16:44, 8F
→
10/31 16:45, , 9F
10/31 16:45, 9F
→
10/31 23:34, , 10F
10/31 23:34, 10F
→
10/31 23:39, , 11F
10/31 23:39, 11F
→
10/31 23:45, , 12F
10/31 23:45, 12F
→
10/31 23:47, , 13F
10/31 23:47, 13F
推
11/01 00:11, , 14F
11/01 00:11, 14F
→
11/01 00:12, , 15F
11/01 00:12, 15F
→
11/01 00:13, , 16F
11/01 00:13, 16F
→
11/01 00:13, , 17F
11/01 00:13, 17F
→
11/01 02:42, , 18F
11/01 02:42, 18F
→
11/01 02:42, , 19F
11/01 02:42, 19F
→
11/01 02:42, , 20F
11/01 02:42, 20F
→
11/01 02:59, , 21F
11/01 02:59, 21F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章