Can I access the structure inside the structure without using the point operator?

I have 2 structures in which 90% of their fields are the same. I want to group these fields in a structure, but I do not want to use the point operator to access them. The reason is that I am already encoded with the first structure and just created the second.

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 structure:

typedef struct{
  int a;
  int b;
  int c;
} str3;

and change str1 and atr2 to this:

typedef struct{
  str3 str;
  object1 name;
} str1;

typedef struct {
  str3 str;
  object2 name;
} str2;

Finally, I would like to have access to 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 any way to do this. The reason for this is because I want to save integrety from the data if there were changes in the structure and not repeat myself and change my existing code and not have too deeply nested fields.

RESOLVED: . , , :

struct str11
{
int a;
int b;
int c;
};
typedef struct str22 : public str11
{
QString name;
}hi;

+3
6

. , C- , ++:

struct str3{
  int a;
  int b;
  int c;
};

struct str2 : public str3{
  object2 name;
};
+10

.

struct
{
  int a;
  int b;
  int c;
} str3;

str3, str3.

, ,

struct str1
{
  int a;
  int b;
  int c;
};


struct str2 : public str1
{
  object1 name;
};  
+3

, integrety ,

, , , , :

class DataHolder {
    int a_, b_, c_;
public:
    int a() const { return a_; }
    int b() const { return b_; }
    int c() const { return c_; }
};

class User : public DataHolder {
    object o_;
public:
    object& getObject() { return o_; }
};
+2

++ ( ++), C . GCC 4.3 , , -ansi -std=c99. -std=c++98:


int main (int argc, char *argv[])
{
    struct
    {
        struct
        {
            int a;
            int b;
            int c;
        };
        int test;
    } global;

    global.a = 1;
    global.b = 2;
    global.c = 3;
    global.test = 4;

    return global.b;
}
+1

, . , a.. . , / ( 1 /).

0

You can do this using GCC, like other posters, but in addition to this, you can use a flag -fms-extensionsthat allows you to use the previously defined structas an unnamed field.

More details here .

0
source

Source: https://habr.com/ru/post/1744854/


All Articles