accessing member of structure within a class

2019-05-03 07:40发布

I have an .hpp and .cpp file. I want to access the variable in the structure within a class which happens to be in the header .hpp file, in the .cpp file.

In .hpp, I have

class foo{

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

};

 foo(const char*name)
:m_name(name){}

In .cpp I did:

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

On doing this I receive the following error:

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

My objective is to get the values of x and y in the cpp file. Any suggestion/idea will be really appreciated.

Thanks.

10条回答
Juvenile、少年°
2楼-- · 2019-05-03 08:24

In .hpp you need to declare a variable with the struct type. For example,

packet Packet;

inside of your class

In .cpp, try this

foo *foo_ptr = new foo; // creating new foo object in the heap memory with a pointer  foo_ptr
printf("The value of x is : %d",foo_ptr->Packet.x);
printf ("The value of y is : %u", foo_ptr->Packet.y);
查看更多
仙女界的扛把子
3楼-- · 2019-05-03 08:28

You have just defined struct. Try something like this -

struct packet{
int x;
u_int y;
}test;

and in your cpp, access your struct elements like this -
foo_1.test.x

查看更多
做个烂人
4楼-- · 2019-05-03 08:30

In your class Foo, you have defined a packet struct, but you have not declared any instances of it. What you want is (this is a compileable self-contained example):

#include <iostream>

class Foo {
public:
  struct Packet{
    Packet() : x(0), y(0) {}
    int x;
    int y;
  } packet;
};

int main(int, char**)
{
  Foo foo_1;
  std::cout << "The value of x is: " << foo_1.packet.x << std::endl;
  std::cout << "The value of y is: " << foo_1.packet.y << std::endl;
}
查看更多
相关推荐>>
5楼-- · 2019-05-03 08:31

You declare the struct, but you never put any data in it.

查看更多
登录 后发表回答