访问类中的结构成员

Qui*_*ver 5 c++ struct pointers structure class

我有一个.hpp和.cpp文件.我想访问类中的结构中的变量,该类恰好位于.cpp文件中的头.hpp文件中.

在.hpp,我有

class foo{

public:
       struct packet{
         int x;
         u_int y;
      };

};

 foo(const char*name)
:m_name(name){}
Run Code Online (Sandbox Code Playgroud)

在.cpp我做了:

foo *foo_1 = &foo;
printf("The value of x is : %d",foo_1->packet.x);
printf ("The value of y is : %u", foo_1->packet.y);
Run Code Online (Sandbox Code Playgroud)

这样做我收到以下错误:

code_1.cpp:117: error: expected primary-expression before ‘;’ token
code_1.cpp:118: error: invalid use of ‘struct foo::packet’
code_1.cpp:119: error: invalid use of ‘struct foo::packet’
make: *** [code_1] Error 1
Run Code Online (Sandbox Code Playgroud)

我的目标是在cpp文件中获取x和y的值.任何建议/想法将非常感激.

谢谢.

Mar*_*cia 8

你需要一个成员对象类型foo::packetclass foo.

class foo{

public:
      struct packet{
         int x;
         u_int y;
      };

      packet my_packet;   // <- THIS
};
Run Code Online (Sandbox Code Playgroud)

在你的.cpp中,你应该这样做:

foo *foo_1 = &foo;
printf("The value of x is : %d",foo_1->my_packet.x);
printf ("The value of y is : %u", foo_1->my_packet.y);
Run Code Online (Sandbox Code Playgroud)

您必须记住,即使packet是在内部foo,它也不foo作为成员对象包含在内.它只是一个封闭在另一个类中的类.对于要使用的类,您必须具有它的对象(也可以在没有对象的情况下使用类,但是,好吧......).