Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a variable with the same type as a variable in a struct

Tags:

c++

variables

In c++ say I have a structure defined in a header file.

******test.h***********
typedef struct mystruct{
    uint8_t num;
} mystruct;

In another header file, say myclass.h, I want to define a variable which has the same type (uint8_t) as the field "num" in mystruct.

******myclass.h***********
class myclass{
public:
    ??? num;
};

Is there a way to define such a variable? Thanks.

like image 689
user2565858 Avatar asked Jan 18 '26 10:01

user2565858


2 Answers

Using C++11, you can use decltype:

class myotherclass
{
public:
  decltype (myclass::num) otherNum;
};

Without using C++11, the typical way I have done this is to take a kind of step back. Create a typedef:

typedef uint8_t MyIntegral;

And then use that same type in both classes:

class myclass
{
public:
  MyIntegral num;
};

class motherclass 
{
pulic:
  MyIntegral othernum;
};

This isn't exactly what you were asking for, but if you can change the definition of myclass you may find this approach to be more maintainable.

like image 146
John Dibling Avatar answered Jan 21 '26 02:01

John Dibling


You have to define the type in your first class, and then access it from the other class

******test.h***********

struct mystruct{
    typedef uint8_t num_t;
    num_t num;
};

And

******myclass.h***********
class myclass{
public:
    mystruct::num_t num;
};
like image 28
Antonio Avatar answered Jan 21 '26 00:01

Antonio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!