PDA

View Full Version : array of typedef struct declared inside class



Ryuuji
22nd November 2012, 03:00
Hi everyone!


I'm encountering problem about typedef struct. The case was i declared a struct inside a class like this:

class Myclass
{
private:

typedef struct MysampleStruct{
int x;
int y;
}Mysample[3];
}

If I'm going to use this struct like this:

Mysample[0].x = 1;

I'm having an error like "expected unqualified-id '[' token".

But if I'm gonna delete the 'typedef' in 'typedef struct MysampleStruct', its working fine.

Can someone explain to me why these happen?

Thanks in advance.

wysota
22nd November 2012, 05:47
If you use typedef then you need to pass the new name too (which you didn't). But in general in C++ typedefing structs doesn't make sense since structs are equivalent to classes so you can access the struct using just its name (without prepending it with 'struct').

Ryuuji
22nd November 2012, 05:59
If you use typedef then you need to pass the new name too (which you didn't). .

Hi Sir, about the quoted above? How will I pass the new name? Sorry if this sounds dumb. I'm new here Sir. Thanks a lot

wysota
22nd November 2012, 06:07
struct MySampleStruct {
int x;
int y;
};

MySampleStruct MySample[3];

or possibly even:


struct {
int x;
int y;
} MySample[3];

Santosh Reddy
22nd November 2012, 07:00
When typedef is used the struct definition should follow with the new typename. You are specifing the variable (array) instead of typename. Correct way to specify is below. Also typedef does not have much use in C++ (as explained by wysota), unless you are porting C based code, and don,t want to change it.



class Myclass
{
private:
struct MysampleStruct{
int x;
int y;
}Mysample[3];
};
// or
class Myclass
{
private:
typedef struct MysampleStruct{
int x;
int y;
}MysampleStructType;

MysampleStructType Mysample[3];
};