Class C++

Hi everyone! In this class example i can use N in the constructor, however in the function it doesn't work. What is the solution to this? P.S (I don't want to pass in the parameter in the function, cause i wasn't asked to).
Thank you in advance!

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
class OneDComplexMatrix {

private:
	Complex * ptr;
	int N;

public:

	// Constructor (dynamic memory allocation) 
	OneDComplexMatrix(int N) {
		ptr = new Complex[N];

		// sets real & imag values to zero
		for (int i = 0; i < N; i++) {				// Here it works!
			ptr[i].setValues(0,0);
			ptr[i].print(); // debugging 
		}
	}
	
	void setRandomValues(int min, int max) {
		// initialize random seed
		srand((unsigned)time(NULL));
		for (int i = 0; i < N; i++) {				//<=========== Can't use N?!
			ptr[i].setValues((rand() % (2 * max + 1) + (min)), (rand() % (2 * max + 1) + (min)));
			ptr[i].print(); // debugging
		}
	}
Last edited on
Which N? There are two.

The first one is introduced on line 5. That is the member of class OneDComplexMatrix.

The other one appears on line 10. A parameter of the function. It hides (masks) the member N within the body of the function (lines 11-17). You could refer to the member N within the constructor with syntax: this->N.

You can use the member N on lone 23 just fine. Your problem is that you never initialize it with a known value.

Thank you for your quick response!
Topic archived. No new replies allowed.