将两个大数字表示为链表

问题描述 投票:1回答:1

我试图将2个大数字相乘,表示为链接lilsts(重载运算符*),但似乎有错误。你能帮助我吗?我认为乘法函数是正确的,因为我已经测试过了。但是,当我试图超载操作员时,我似乎无法指出什么是错误的......我已经尝试在一个列表中循环并且与另一个节点中的每个节点一起使用..额外的分割提示2大数?谢谢!这是我的代码:

Numar *Numar :: operator* (Numar *nr2) //overloading operator*
{
Lista *L = new Lista;
Numar *rezultat = new Numar(L);//links the list to the number 
Lista *aux = new Lista;
Numar *rez2 = new Numar(aux); //an auxiliary 
int t = 1;
Nod *p2 = this->L->prim; //1st node of this
while (p2) //loop the 2nd number
{
rez2 = nr2->multiply(p2->info * t); //multiply the 1st list with an int
cout<<"rez2 "<<rez2;
rezultat = *rezultat + rez2;
cout<<"rezultat "<<rezultat;
t *= 10; //that carry 
p2 = p2->next;
}
return rezultat;
}

完整代码https://pastebin.com/PcXuM9EL

c++ list overloading operator-keyword
1个回答
1
投票

问题是这个定义不适用于你打算做的事情;

Numar *Numar :: operator* (Numar *nr2) 

如果要定义类型Numaroverload arithmetic operators,则需要处理值(最终是const或rvalue引用)而不是指针。否则,只要进行一些临时计算,就会泄漏内存。

因此,您需要修改代码设计,以便最终得到以下签名:

Numar Numar :: operator* (Numar nr2) 

为此,NumarLista需要实施rule of 3

编辑:为了避免在没有必要时复制值,您可能需要 - 正如评论中的1201programalarm所建议的那样:

Numar Numar :: operator* (const Numar& nr2) 

但是,鉴于const,在nr2上调用的成员函数的定义中可能需要一些规则。

© www.soinside.com 2019 - 2024. All rights reserved.