Hello, I am having some trouble using references (int & foo;) to work the way I want them to. I am trying to use them as a was to #define a static class vector as a more simple vector (ie, typing foo[#] instead of classname::foo[#]). Doing it with a #define is pretty simple, but I am just trying not to use too many macros. Some sample code for assistance.
#ifndef test_h
#define test_h
#include <vector>
// just some class
class foo
{
public:
// the public vector, foo::foo_vector[#];
static std::vector<int> foo_vector;
};
// want this to be bar[#];
std::vector<int> & bar = foo::foo_vector;
// alternative way that I don't like, but it DOES work
// #define bar foo::foo_vector
#endif
test.cpp
1 2 3
#include "test.h"
// declare static members
std::vector<int> foo::foo_vector;
main.cpp
1 2 3 4 5 6 7 8 9 10
#include <iostream>
#include "test.h"
int main(int args, char** argc)
{
// test to see if it works
bar.push_back(10);
std::cout << bar[0];
while(1); return 0;
}
The code with the #define did work. The code with the reference did not work. If you have another way of doing it, I would love to hear. Thank you :D
test.h defines bar, it doesn't just declare it. Since your program #includes test.h in two files (test.cpp and main.cpp) you end up with two definitions of the same variables and that's illegal.
A public static member differs from a global variable only in scope. If you define a global reference to the same data, then what's the point of putting the original data in a class in the first place? Specifically, if bar is public, then why not just make foo_vector public too?
Let's go back to your original problem. You want to avoid typing foo::foo_vector all the time. That's understandable, but to deal with it, create the reference closer to where you want to use it. In other words, move line 15 from test.h to line 6 of main.
Thank you dhayden for the reply. What you said in paragraph 2 makes a lot of sense, and I guess I only wanted the member to be static in the class for organization and not function. Moving it to be global may be the proper response. As for paragraph 3, moving the reference to int main is not something possible with my code. Thank you again thou :D
I will leave this open for another few hours to see if anyone else has any alternative suggestions.
Don't get me wrong - putting the data inside the class is a fine idea. I'm just saying that if you want a reference as a shorthand way to access it, then create the reference when you need it, not at the global scope.