访问类中的结构的成员 [英] accessing member of structure within a class
问题描述
我有一个.hpp和.cpp文件。我想访问一个类中的结构中的变量,恰好在.hpp文件的头文件中,在.cpp文件中。
在.hpp中,我有
class foo {
public:
struct packet {
int x;
u_int y;
};
};
foo(const char * name)
:m_name(name){}
在.cpp中我做了:
foo * foo_1 =& foo;
printf(x的值是:%d,foo_1-> packet.x);
printf(y的值是:%u,foo_1-> packet.y);
这样做时,我收到以下错误:
code_1.cpp:117:错误:期望的主表达式';'令牌
pre>
code_1.cpp:118:错误:无效的使用'struct foo :: packet '
code_1.cpp:119:错误:无效使用'struct foo :: packet'
make:*** [code_1]错误1
我的目标是获取cpp文件中x和y的值。
感谢。
解决方案您需要在
类foo
中 c>类型foo :: packet
/ p>
class foo {
public:
struct packet {
int x;
u_int y;
};
packet my_packet; //< - THIS
};
在您的.cpp中,您应该执行:
foo * foo_1 =& foo;
printf(x的值是:%d,foo_1-> my_packet.x);
printf(y的值为:%u,foo_1-> my_packet.y);
您必须记住,即使
包
在foo
中,它不包括在foo
中作为成员对象。它只是一个封装在另一个类中的类。对于要使用的类,你必须有它的对象(一个类也可以使用没有它的对象,但是,好...)。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.
解决方案You need a member object of type
foo::packet
inclass foo
.class foo{ public: struct packet{ int x; u_int y; }; packet my_packet; // <- THIS };
In your .cpp, you should do:
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);
You must remember that even though
packet
is insidefoo
, it is not included infoo
as a member object. It is just a class enclosed inside another class. And for a class to be used, you must have objects of it (a class can also be used without having objects of it, but, well...).这篇关于访问类中的结构的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!