I'm new with c++ and I've been meaning to implement vector calculations via operator overloading. The code that's not functioning as I intended is this.
First, main.cpp
#include <iostream>
#include "MyVector.h"
#include "MyVector.cpp"
int main() {
double forvector1[] = {0.1,0.2,0.3};
double forvector2[] = {0.2,0.3,0.5};
MyVector vector1(forvector1,3);
MyVector vector2(forvector2,3);
MyVector temp = vector1 + vector2;
temp.print();
return 0;
}
Then, MyVector.cpp
#include "MyVector.h"
#include <iostream>
using namespace std;
MyVector::MyVector(double numList[], int size) : numList(numList), size(size) {
}
MyVector::MyVector(){ //empty vector;
}
void MyVector::print(){
cout<<"("<<numList[0];
for(int i=1;i<size;i++){
cout<<", "<<numList[i];
}
cout<<")"<<endl;
}
MyVector MyVector:: operator+(MyVector vec){
if(vec.size != size){
cout<<"+ cannot be applied to ";
cout<<"("<<numList[0];
for(int i=1;i<size;i++){
cout<<", "<<numList[i];
}
cout<<") and ";
vec.print();
return MyVector();
}
double tempList[size];
for(int i=0;i<size;i++)
{
tempList[i]=numList[i]+vec.numList[i];
}
MyVector result(tempList,size);
return result;
}
Finally, this is my MyVector.h
class MyVector{
private:
int size;
double * numList;
public:
MyVector(double numList[], int size); //size>=1
MyVector(); //empty Vector
void print(); //print its content e.g. (1, 2, 3, 4)
MyVector operator-(MyVector vec);
MyVector operator+(MyVector vec);
double operator*(MyVector vec);
MyVector operator/(MyVector vec);
//You may add more member functions as well
};
#endif // MYVECTOR_H_INCLUDED
According to the main.cpp, I should be getting (0.3, 0.5, 0.8) for the output. However, I keep getting (0.3, 0, 2.12199e-314), which means probably only the first element of the result array was right. I'm guessing it's because of the pointer I used to point at the array, so that's why only the first element was correct. Is there any way I could make the operator+ work? Any help would be appreciated. Thanks!
double tempList[size];, is NOT permitted according to the C++ Standard. It's allowed as a language extension by a number of compilers, but comes with some risks and limitations, so you use it at your own risk.