简体   繁体   中英

Why is my method with array parameter not working properly? (C++)

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!

My guess would be that there is a dangling pointer.

double tempList[size];
for(int i=0;i<size;i++)
{
    tempList[i]=numList[i]+vec.numList[i];
}
MyVector result(tempList,size);
return result;

tempList points to data that are local to the function, but result uses it. In your constructor, you should copy the data in the array into another array owned by the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM