haddad
haddad

Reputation: 1

How do I declare a struct within a class?

I want to declare a struct within a class which is private and I want to give a character value to a variable in the same struct, but I can't initialize it or cin it:

class puple
{
private:
    struct p
    {
        char name[25];
        int grade;
    };
public:
    puple(){};
    void setme()
    {
        this->p::grade=99;
        this->p::name[25]='g';  //here is the problem
    }
    void printme()
    {
        cout<<"Name:  "<<this->p::name<<endl;
        cout<<"Grade:  "<<this->p::grade<<endl;
    }
};
void main()
{
    puple pu1;
    pu1.setme();
    pu1.printme();
}

Upvotes: 8

Views: 30888

Answers (4)

jkerian
jkerian

Reputation: 17016

You have two serious problems here

struct p
{
char name[25];
int grade;
};

This defines a struct type, named p. I think what you wanted to do was

struct
{
char name[25];
int grade;
} p;

This will declare a struct, named p, with the name and grade member variables.

Your second serious problem is that you assign:

this->p::name[25]='g';  //here is the problem

This assigns 'g' to the 26th element of the array name. (arrays are 0-indexed)

Upvotes: 14

Will Bickford
Will Bickford

Reputation: 5386

Place the struct definition outside of the class using a typedef. By having the struct defined in your .cpp file it will not be visible outside of your class.

#include <iostream>
typedef struct _foo
{
    int a;
} foo;

class bar
{
public:
  void setA(int newa);
  int getA();
private:
    foo myfoo;
};

void bar::setA(int newa)
{
   myfoo.a = newa;
}

int bar::getA()
{
   return myfoo.a;
}

using namespace std;
int main()
{
  bar mybar;
  mybar.setA(17);
  cout << mybar.getA() << endl;
  return 0;
}

Upvotes: 5

THX-1138
THX-1138

Reputation: 21730

isn't it

struct { ... } p; // variable of struct-type definition.

not

struct p { ... }; // type 'struct p' definition.

?

Upvotes: 6

Doug T.
Doug T.

Reputation: 65589

You've describe a type called "p" which is a struct. There is yet no thing of type p around. Therefore your

p->...

calls make no sense.

Try declaring

p pInstance;

in your class and using it, ie:

void setme()
{
    this->pInstance.grade=99;
    this->pInstance.name[25]='g';  //here is the problem
}

Note even with this your assignment to name[25] will fail as the allowed indices for that array are 0 up to 24 (totalling 25 elements).

Upvotes: 20

Related Questions