### Program not working. 3D vectors.

I am trying to create a 3-D cartesian vector class, with a magnitude function, copy constructor, sum operator and accessible x,y,z, coordinates. Strangely it's not working.

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950`` ``````#include #include #include #include using std::cout; using std::cin; using std::endl; class vectr { public: float x, y, z; vectr() {}; vectr(float a, float b, float c) : x(a), y(b), z(c) {}; vectr(const vectr&); float magnitude() {return sqrt(x * x + y * y + z* z);} vectr operator+(vectr& other) { vectr temp; temp.x += other.x; temp.y += other.y; temp.z += other.z; return temp;} }; vectr::vectr(const vectr& v){ vectr v (v.x, v.y, v.z); } int main() { float x, y, z; cout << "Enter for vector A.\n"; cin >> x >> y >> z; vectr A (x, y, z); cout << "Enter for vector B.\n"; cin >> x >> y >> z; vectr B (x, y, z); vectr C = A+B; cout << "A + B = " << "<" << C.x << ", " << C.y << ", " << C.z << ">\n"; cout << "|A| = " << A.magnitude() << endl; cout << "|B| = " << B.magnitude() << endl; cout << "|A+B| = " << C.magnitude() << endl; return 0; }``````

Any suggestions?
I would suggest you tell us how it's "not working".
Last edited on
yeah sorry, it says " error C2082: redefinition of formal parameter 'v'"
try this as your copy constructor:

 ``123456`` ``````vectr::vectr(const vectr& v){ x = v.x; y = v.y; z = v.z; }``````
Or better yet

`vectr(const vectr& v) : x(v.x), y(v.y), z(v.z) {}`

:)

Though your actual problem is you are using "v" as the name for both the local vector and for the parameter vectr... which is a error.

 ``123`` ``````vectr::vectr(const vectr& v){ vectr v (v.x, v.y, v.z); }``````

Though your current copy ctor doesn't make sense since you are just initializing a local copy of the vector which will be destroyed and nothing happens.

I would suggest looking up how copy ctors work a bit more so you understand them better. Here is a few links that might help.

http://www.cplusplus.com/articles/y8hv0pDG/
http://en.cppreference.com/w/cpp/language/copy_constructor
http://www.codeproject.com/Tips/78946/C-Copy-Constructor-in-depth

Wish you the best of luck with your project.
Last edited on
Topic archived. No new replies allowed.