
How to use alias within a structure?
{ Followups set to clc++,clc++m to reduce clutter in other groups. -jep }
Quote:
> I want alias a variable within a structure, ie. an integer refered to as
> hieght or weight depending on the context. I'm having touble with the
> syntax.
> typedef struct
> {
> int weight;
> int &height = weight; // alway gets syntax error here
> ......
> }
> my_data_type;
> Strangely enough, I have no problem with aliasing a single variable such
> as:
> int iv;
> int &rv = iv;
> Please help me out by kindly showing me some examples. Thanks.
The simple answer is: You can't. A reference is (conceptually) more like a
pointer than a simple alias. For example, you could do the following:
int &z = (x > y) ? x : y;
In case you are unfamiliar with the ?: operator, this code section makes z
into a reference to the bigger of x and y. The way most C++ programmers
would approach your problem is through member functions:
struct my_data_type { // No need for typedefs in C++
int weight_or_height;
int get_weight(void) { return weight_or_height; }
void set_weight(int i) { weight_or_height = i; }
int get_height(void) { return weight_or_height; }
void set_height(int i) { weight_or_height = i; }
Quote:
};
You can now do the following:
my_data_type my_variable;
my_variable.set_weight(5);
printf("Weight = %d Height = %d\n", my_variable.get_weight(),
my_variable.get_height());
Another way of doing the same thing with shorter syntax is:
struct my_data_type {
int weight_or_height;
int &weight(void) { return weight_or_height; }
int &height(void) { return weight_or_height; }
Quote:
};
my_data_type my_variable;
my_variable.weight() = 5;
printf("Weight = %d Height = %d\n", my_variable.weight(),
my_variable.height());
If you use this syntax, you can use weight and height like in your original
program, you just have to remember to add parenthesis. Both of these
solutions should have all their functions inlined, so they are not any
slower or more wasteful than your original code. In fact, they use less
space, since references take as much space as pointers, that is 4 bytes on
most computers.
--
[ about comp.lang.c++.moderated. First time posters: do this! ]