Reputation: 71
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.
Upvotes: 3
Views: 116
Reputation: 101456
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.
Upvotes: 5
Reputation: 20286
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;
};
Upvotes: 3