I have 2 structures that have 90% of their fields the same. I want to group those fields in a structure but I do not want to use the dot operator to access them. The reason is I already coded with the first structure and have just created the second one.
before:
typedef struct{
int a;
int b;
int c;
object1 name;
} str1;
typedef struct{
int a;
int b;
int c;
object2 name;
} str2;
now I would create a third struct:
typedef struct{
int a;
int b;
int c;
} str3;
and would change the str1 and atr2 to this:
typedef struct{
str3 str;
object1 name;
} str1;
typedef struct {
str3 str;
object2 name;
} str2;
Finally I would like to be able to access a,b and c by doing:
str1 myStruct;
myStruct.a;
myStruct.b;
myStruct.c;
and not:
myStruct.str.a;
myStruct.str.b;
myStruct.str.c;
Is there a way to do such a thing. The reason for doing this is I want keep the integrety of the data if chnges to the struct were to occur and to not repeat myself and not have to change my existing code and not have fields nested too deeply.
RESOLVED: thx for all your answers. The final way of doing it so that I could use auto-completion also was the following:
struct str11
{
int a;
int b;
int c;
};
typedef struct str22 : public str11
{
QString name;
}hi;
First one remark. This
defines an object str3, not a type str3.
You can achieve what You want using inheritance, but I suggest changing the numbers of Your structs
Yes. Rather using a C-style of inheritance, using C++ style:
I'm not sure about C++ (I'm still learning C++) but in C, some compilers allow anonymous structs. With GCC 4.3, the following compiles with no errors when no flags are specified, but fails to compile with
-ansi
or-std=c99
. It compiles successfully with-std=c++98
however:Don't use silly tricks to avoid proper refactoring. It will save you a little bit of typing but it will bite in your a.. later. If it is that complicated to edit, then you're a using the wrong tools and/or you have a bad naming scheme (1 letter names are difficult to find/replace).
You can do it with GCC, as other poster mentioned, but in addition to this you can use
-fms-extensions
flag that allows you to use earlier definedstruct
as unnamed field.More here.
To achieve that i'd rather use proper encapsulation, accessors and inheritance to make changes in layout invisible from user code: