以下代码给出了垃圾输出(任意整数值)。重载的#include<iostream>
using namespace std;
class vector
{
int num;
int ele[20];
public:
friend istream& operator>>(istream&,vector&);
friend ostream& operator<<(ostream&,vector&);
vector operator+(vector&);
};
istream& operator>>(istream& is,vector& v)
{
is >> v.num;
for(int i = 0;i < v.num; i++)
{
is >> v.ele[i];
}
return is;
}
ostream& operator<<(ostream& os,vector& v)
{
for(int i = 0;i < v.num; i++)
{
os << v.ele[i] << endl;
}
return os;
}
vector vector::operator+(vector& v)
{
vector v2;
if(num == v.num)
{
for(int i = 0;i < v.num; i++)
{
v2.ele[i] = ele[i] + v.ele[i];
cout << v2.ele[i] << endl;
}
return v2;
}
}
int main()
{
vector v1,v2,v3;
int i, j;
cin>>v1;
cin>>v2;
cin>>i;
cin>>j;
v3 = v1+v2;
cout<<v3;
}
最佳答案
您无法在v2.num
中将值设置为vector vector::operator+(vector& v)
,因此进行设置。
另外,您还应该在每个非无效函数的控制路径上显式返回某些内容。
vector vector::operator+(vector& v)
{
vector v2;
if(num == v.num)
{
v2.num = num; // add this
for(int i = 0;i < v.num; i++)
{
v2.ele[i] = ele[i] + v.ele[i];
cout << v2.ele[i] << endl;
}
}
else // add this section
{
v2.num = 0;
}
return v2; // move this
}
关于c++ - 使用运算符重载的程序产生垃圾输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35967067/