Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct in class

Tags:

c++

class

struct

I have struct in class and not know how to call variables from struct, please help ;)

#include <iostream>
using namespace std;

class E
{
public: 
    struct X
    {
        int v;
    };
};

int main(){

E object;
object.v=10; //not work 

return 0;
}
like image 788
Wizard Avatar asked Dec 18 '11 08:12

Wizard


2 Answers

I declared class B inside class A, how do I access it?

Just because you declare your struct B inside class A does not mean that an instance of class A automatically has the properties of struct B as members, nor does it mean that it automatically has an instance of struct B as a member.

There is no true relation between the two classes (A and B), besides scoping.


struct A { 
  struct B { 
    int v;
  };  

  B inner_object;
};

int
main (int argc, char *argv[]) {
  A object;
    object.inner_object.v = 123;
}
like image 108
Filip Roséen - refp Avatar answered Oct 13 '22 19:10

Filip Roséen - refp


It's not clear what you're actually trying to achieve, but here are two alternatives:

class E
{
public:
    struct X
    {
        int v;
    };

    // 1. (a) Instantiate an 'X' within 'E':
    X x;
};

int main()
{
    // 1. (b) Modify the 'x' within an 'E':
    E e;
    e.x.v = 9;

    // 2. Instantiate an 'X' outside 'E':
    E::X x;
    x.v = 10;
}
like image 25
Johnsyweb Avatar answered Oct 13 '22 19:10

Johnsyweb