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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <vector>
#include <string>
#include <cmath>

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 <x, y, z> for vector A.\n";
	cin >> x >> y >> z;
	vectr A (x, y, z);
	cout << "Enter <x, y, z> 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:

1
2
3
4
5
6
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.

1
2
3
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.