I have read some article on Stackoverlow like How to “return an object” in C++? about this problem but my problem still exists.
My program implements a Vector Class (vector in Maths). I want to overload an operator +
, I have try to modify empty object in function or use static member and the results is in my comments on these code below.
This is my code:
#include <iostream>
class Vector {
double * arr;
unsigned short dim;
public:
Vector(const int& d = 0); // This constructor initialize memory for its member
Vector& operator = (const Vector& v);
/* This function must return a Vector object
*
* Example: Vector v = v1 + v2; // v1.arr = {1, 1, 3}, v2.arr = {1, 0, 1}
*
* Then v.arr = {2, 1, 4} // this is just an example
* When I run it by using empty class like:
* Vector operator + (const Vector& v) const {
* Vector vec();
* // Do something with vec;
* return vec;
* }
* It returns a garbage value.
*
* When I run the code below, the GNU compiler inform:
* C:\Desktop>g++ -Wall -ansi -c Vector.cpp
* C:\Desktop>g++ -Wall -ansi -o main.exe main.cpp vector.o
* vector.o:Vector.cpp:(.text+0x33e): undefined reference to `Vector::_vec'
*/
Vector operator + (const Vector& v) const {
if (dim == v.dim) {
_vec = Vector(dim);
for (int i = 0; i < dim; ++i) {
_vec.arr[i] = arr[i] + v.arr[i];
}
return _vec;
}
return Vector(0);
}
~Vector();
private:
static Vector _vec;
};
Main function for anyone needs it:
#include <iostream>
#include "Vector.h"
using namespace std;
int main(int argc, char const *argv[]) {
Vector v(-2), v3;
Vector v2(2);
cout << "Input vector: ";
cin >> v;
cout << v << endl;
cout << "Input vector: ";
cin >> v2;
cout << v2 << endl;
v3 = v + v2;
cout << v3;
return 0;
}
Thanks for reading.