作者bil193 (丁丁)
看板C_and_CPP
标题[问题] 不晓得哪里有问题(C++)
时间Sat Oct 17 12:36:42 2009
小弟在写一个用OOP实作多项式 的程式
可是就一个小地方 debug一个早上还是找不出原因
把所有变数值都印出来,还是不知道为什麽
第一次在main里面执行 a.newTerm(2,4); 是成功的
但下一行再执行 a.newTerm(3,5);
就在termArray[terms].coef=theCoeff; 卡住了,也没说错误,但从这以後
的指令都不跑了,太奇怪了!
另外一件很怪的事
如果我把termArray[terms].coef=theCoeff; 的上一行,也就是:
cout<<"termArray["<<terms<<"].coef="<<termArray[terms].coef<<endl;
注解掉(这只是一个印出目前值,删掉应该无伤大雅),执行时就好像会runtime_error
ps.compiler是Dev C++
这到底是什麽问题啊@@
#include <iostream>
using namespace std;
class Term{
public:
friend class Poly;
double coef;
int exp;
};
class Poly{
public:
Term* termArray;
int capacity;
int terms;
void newTerm(double theCoeff,int theExp)
{
cout<<"Enter function newTerm theCoeff:"<<theCoeff<<" theExp:"<<theExp<<endl;
if(terms<=capacity-1)
{
cout<<"Enter if statement."<<endl;
capacity*=2;
cout<<"Now capacity:"<<capacity<<endl;
Term* temp=new Term[capacity];
copy(termArray,termArray+terms,temp);
termArray=temp;
delete[] temp;
}
cout<<"termArray["<<terms<<"].coef="<<termArray[terms].coef<<endl;
termArray[terms].coef=theCoeff;
cout<<"termArray["<<terms<<"].coef="<<termArray[terms].coef<<endl;
termArray[terms++].exp=theExp;
cout<<"---Information list---"<<endl;
cout<<"term:"<<terms<<endl;
cout<<" capacity:"<<capacity<<endl;
cout<<" ["<<terms-1<<"]"<<": " <<endl;
cout<<"coef:"<<termArray[terms-1].coef<<endl;
cout<<"exp:"<<termArray[terms-1].exp<<endl<<endl;
}
Poly():terms(0),capacity(1){}
};
int main()
{
Poly a,b;
a.newTerm(2,4);
a.newTerm(3,5);
a.newTerm(4,6);
a.newTerm(5,7);
system("pause");
return 0;
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 112.104.15.86
1F:推 janice001:上色的挺好看的.. 10/17 12:50
2F:→ bil193:是用置底文:[公告] 张贴程式码 里面的网址的啦 10/17 12:54
3F:推 ledia:是不是应该 terms == capacity 才加倍呀 ? 10/17 12:56
4F:→ ledia:or 至少是 terms >= capacity - 1 之类的 10/17 12:57
5F:→ bil193:改成terms>=capacity-1 之後 还是一样卡在原来的地方耶@@ 10/17 13:01
6F:→ bil193:多谢提醒:) 10/17 13:02
7F:推 janice001:噗 原来如此 XD 10/17 13:20
8F:推 snowlike:new空间给temp,然後交给termArray,然後把该空间回收.. 10/17 13:24
9F:推 tiyun:应该是delete[] termArray; 再termArray=temp; ? 10/17 14:26
10F:→ bil193:谢谢各位 用楼上的方式就可以了 10/17 17:30