Getting rid of Globals.

Pages: 12
Not as easy as it sounds. You need to look up the "right left rule":
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
#include <iostream>

class A
{
	int((&ref)[2])[2];

public:
	A(int((&ref)[2])[2]): ref(ref) {}

	void func()
	{
		std::cout << ref[1][1] << '\n';
	}

};

int main()
{
	int array[2][2];

	array[1][1] = 5;

	A a(array);

	a.func();
}
Yikes, think I'll find me a way around this then. Thanks!
Slightly less intimidating is passing a pointer to the array rather than a reference:
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
#include "test.h"

class A
{
	int(*arr)[2];

public:
	A(int(*arr)[2]): arr(arr) {}

	void func()
	{
		std::cout << arr[1][1] << '\n';
	}

};

int main()
{
	int array[2][2];

	array[1][1] = 5;

	A a(array);

	a.func();
}


Alternatively (and much preferred) use a std::vector:
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
#include <vector>
#include <iostream>

class A
{
	std::vector<std::vector<int> >& vec;

public:
	A(std::vector<std::vector<int> >& vec): vec(vec) {}

	void func()
	{
		std::cout << vec[1][1] << '\n';
	}

};

int main()
{
	std::vector<std::vector<int> > vec(2, std::vector<int>(2));

	vec[1][1] = 5;

	A a(vec);

	a.func();
}
Last edited on
Due to some responses in my other topic, I've replaced (most of) my C-arrays with std::valarrays, which (like vectors) are properly reference-able without mad voodoo, so consider your advice taken!

I've completely gotten rid of the 2D array after a convincing argument made by Cubbi that the underlying calculations are the same anyway.
Topic archived. No new replies allowed.
Pages: 12