struct in class

2019-02-06 06:29发布

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;
}

标签: c++ class struct
5条回答
神经病院院长
2楼-- · 2019-02-06 06:34

You should define the struct out of the class like this:

#include <iostream>
using namespace std;
struct X
{
        int v;
};
class E
{
public: 
      X var;
};

int main(){

E object;
object.var.v=10; 

return 0;
}
查看更多
狗以群分
3楼-- · 2019-02-06 06:43

If you give the struct no name it will work

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

Otherwise write X x and write e.x.v

查看更多
太酷不给撩
4楼-- · 2019-02-06 06:50

Your E class doesn't have a member of type struct X, you've just defined a nested struct X in there (i.e. you've defined a new type).

Try:

#include <iostream>

class E
{
    public: 
    struct X { int v; };
    X x; // an instance of `struct X`
};

int main(){

    E object;
    object.x.v = 1;

    return 0;
}
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-02-06 06:54

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;
}
查看更多
Viruses.
6楼-- · 2019-02-06 06:56

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;
}
查看更多
登录 后发表回答