I haven’t programmed in c++ for a while, and I was never a very good programmer to begin with. I’m trying to overload a ‘+’ operator for a class ‘MyVector’ that I am writing. Here’s the text for the header file “MyVector.h”:
class MyVector
{
public:
double* data;
MyVector();
MyVector(int size);
~MyVector();
void resize(int n);
int SizeOfData;
MyVector operator + (const MyVector&);
};
And here’s the function that doesn’t seem to work:
MyVector MyVector::operator + (const MyVector& vec)
{
MyVector OutputSum(vec.SizeOfData);
if (vec.SizeOfData != SizeOfData)
{
cout << "Incompatible vector size!n";
return *this;
}
for (int i = 0; i < SizeOfData; i++)
{
OutputSum.data[i] = vec.data[i] + data[i];
}
return OutputSum;
}
I tried running this using the following code:
int main()
{
MyVector vec1(3);
MyVector vec2(3);
MyVector vec3(3);
vec1.data[0] = 0;
vec1.data[1] = 1;
vec1.data[2] = 2;
vec2.data[0] = 3;
vec2.data[1] = 4;
vec2.data[2] = 5;
vec3 = vec1 + vec2;
std::cout << vec3.data[0]<<" "<<vec3.data[1]<<" "<<vec3.data[2]<<"n";
return 0;
}
But the program crashes after the ‘vec3 = vec1 + vec2″ line. For some reason although the overloaded operator function calculates the sum of vec1 and vec2, it returns nonsense, and then crashes. I can’t figure out why. What am I doing wrong?