程序执行不过?

kris2010 2004-11-16 11:15:03
//一元多项式类
#include <iostream>

using namespace std;

class w2
{
public:
w2(int=0);
w2(int, int *, int *);
~w2();
void set(int, int *, int *);
int *get_c() { return c; };
int *get_e() { return e; };
const w2 operator+(const w2 &);

int item;
private:
int *c;
int *e;
};

w2::w2(int item_t)
{
cout<<"constractor\n";
item=item_t;
c=new int [item];
e=new int [item];
for(int i=0; i<item_t; i++)
c[i]=e[i]=0;
}

w2::w2(int item_t, int *array_c, int *array_e)
{
cout<<"constractor\n";
set(item_t, array_c, array_e);
}

w2::~w2()
{
cout<<"destractor\n";
delete [] c;
delete [] e;
}

void w2::set(int i, int *ac, int *ae)
{
item=i;
c=new int [item];
e=new int [item];
c=ac;
e=ae;
}
//it's wrong !!!!
const w2 w2::operator+(const w2 &add_w2)
{
w2 temp(10);

int item_add=0;

for(int i=0; i<add_w2.item; i++)
for(int j=0; j<item; j++){
if(add_w2.e[i]==e[j]){
temp.c[j]=c[j]+add_w2.c[j];
temp.e[j]=e[j];
break;
}
else
if(j==(item-1)){
item_add++;
temp.c[item+item_add-1]=add_w2.c[i];
temp.e[item+item_add-1]=add_w2.e[i];
}
}

return temp;
}

int main()
{
int ac[]={1,2,3,4};
int ae[]={2,3,4,5};
int dc[]={1,2,3,4,5,6};
int de[]={2,3,4,5,6,7};
w2 a(4,ac, ae), d(6, dc, de);
int *c=a.get_c();
int *b=a.get_e();
for(int i=0; i<4; i++)
cout<<c[i]<<' '<<b[i]<<endl;

int i;
w2 temp;
temp=a+d; <-----------没反应,也不报错!

int *temp_c =temp.get_c();
int *temp_e =temp.get_e();

for(i=temp.item; i>=0 && (temp_c[i]!=0 || temp_e[i]!=0); i--)
;
for(int j=0; j<i; i++)
cout<<temp_c[i];

return 0;
}

out:
constractor
constractor
1 2
2 3
3 4
4 5
constractor
constractor
destractor
destractor

请指点一下~谢谢!
...全文
152 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
aa1298 2004-11-19
  • 打赏
  • 举报
回复
没重载 + 运算符.
darkstar21cn 2004-11-17
  • 打赏
  • 举报
回复
别忘了还要重载=,或者一个拷贝构造函数。
nobush 2004-11-17
  • 打赏
  • 举报
回复
前面二位说到了,另外,
w2 temp;
temp=...还需要重载等于符号吧?
你的构造函数w2(int=0);于是这里temp没有分配任何内容。后面也不会有东西打印出来。
kris2010 2004-11-17
  • 打赏
  • 举报
回复
谢谢hunter,我改正了程序。

我用友元重载了operator+,也试过temp=a.operator+(b);可还是一样。
我在temp=a+d;后加了cout<<"go there";用于测试,可并没打印,这是什么原因?
对于之后的语法的错误检查却能进行。如果没重载,编译器会给错误提示。
我用bcc5.5,会不会与之有关。
hunter606 2004-11-17
  • 打赏
  • 举报
回复
void w2::set(int i, int *ac, int *ae)
{
item=i;
c=new int [item];
e=new int [item];
c=ac;
e=ae;
}
以上代碼有問題嗎,是不是由內存洩漏啦?
剛分配內存後指針就被覆蓋了!
hqulyc 2004-11-17
  • 打赏
  • 举报
回复
楼上正解,没重载运算符,+
flyelf 2004-11-16
  • 打赏
  • 举报
回复
temp=a.operator+(b);

可以这么重载
friend w2 operator+(const w2& lhs, const w2& rhs );

w2 operator+(const w2& lhs, const w2& rhs )
{
...
}

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧