运算符重载错误"+" [英] Operator overloading mistake '+'
本文介绍了运算符重载错误"+"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想重载``+''运算符并通过使用vector添加两个系列的元素.但是无论何时我运行代码,向量的第一个元素都变为"inf".我不明白为什么会收到此错误.我几次检查代码是否在填充向量时是否做错了,但我无法找到任何要纠正的东西.有人对此错误有任何想法吗?这是编译后的代码和结果-> http://ideone.com/CA5Q6n [
I wanna overload ''+'' operator and add the elements of two series by using vector. But anytime I run the code , the first elements of my vectors get ''inf'' . I can''t understand why I get this error. I checked my code several time whether I had done mistake while filling vector but I coulnt find anything to correct. Anyone has any idea about this mistake? here is the compiled code and results -> http://ideone.com/CA5Q6n[^]
#include <cstdlib>
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
class Overload {
public:
Overload();
Overload(int);
Overload operator+(Overload &) ;
void SetK(int k);
int GetK() const;
void SetVect(vector<double> vect);
vector<double> GetVect() const;
private:
vector<double> vect ;
int k ;
};
int main(int argc, char** argv) {
Overload a,b(10),c(10) ;
a= b+c ;
cout <<"\nAdded :\n" ;
for(unsigned int i=0;i<a.GetVect().size(); ++i)
cout <<"Res : " << a.GetVect()[i] << endl ;
cout << "first element : "<< a.GetVect()[0] << endl ;
return 0;
}
Overload::Overload() {
k=10 ;
cout << "\nFrist Started\n" ;
for(unsigned int i=0;i<k ; ++i){
double res = 1/pow(i,2) ;
vect.push_back(res);
cout << vect[i] << " " ;
}
cout << "VEctor size : " << vect.size() << endl ;
cout <<"\nfirst ended\n"<< endl ;
}
Overload::Overload(int k) {
double res=0 ;
cout << "\nsecond started : \n" ;
for(unsigned int i=0;i<k ; ++i){
res = 1/pow(i,2) ;
vect.push_back(res);
cout << vect[i] << " " ;
}
cout << "\nsecond ended : \n" ;
}
Overload Overload::operator+(Overload &a){
double res=0 ;
Overload x ;
for(unsigned int i=0 ;i<vect.size();i++) {
res = vect[i] + a.vect[i];
x.vect.push_back(res) ;
}
return x ;
}
void Overload::SetK(int k) {
this->k = k;
}
int Overload::GetK() const {
return k;
}
void Overload::SetVect(vector<double> vect) {
this->vect = vect;
}
vector<double> Overload::GetVect() const {
return vect;
}
推荐答案
在::Overload()
和::Overload(int k)
中,for
循环的第一次迭代都为i=0
计算1/pow(i,2)
.这意味着您最终将除以Inf
值表示的零.
Both in::Overload()
and::Overload(int k)
the first iteration of thefor
loop calculates1/pow(i,2)
fori=0
. Which means you end up dividing by zero which is represented by theInf
value.
这篇关于运算符重载错误"+"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文