[英]Class data member struct : accessing struct members
I have created a simple class called Foo, which contains a data member, Bar, which is a struct. 我创建了一个名为Foo的简单类,它包含一个数据成员Bar,它是一个结构体。
class Foo
{
public :
struct Bar {
int a;
};
};
I'd like to be able to access members in the struct either from functions I define in the class, or from the driver file, but I'm not sure how. 我希望能够从我在类中定义的函数或驱动程序文件中访问结构中的成员,但我不确定如何。 Note: I've declared Bar as a public member because I am trying to access the members directly without using a get function.
注意:我已将Bar声明为公共成员,因为我试图直接访问成员而不使用get函数。 There is method in my madness, but I'll get to that later, so please accept that I want the struct to be public for now.
我的疯狂有方法,但我稍后会谈到,所以请接受我希望结构现在公开。
This is a very stripped down version of a larger program, so please forgive the simplicity. 这是一个大型程序的精简版,所以请原谅简单。
I have created a simple class called Foo, which contains a data member, Bar, which is a struct.
我创建了一个名为Foo的简单类,它包含一个数据成员Bar,它是一个结构体。
Not really. 并不是的。
Foo
doesn't contain any data members at all. Foo
根本不包含任何数据成员。 It just defines a type called Foo::Bar
. 它只定义了一个名为
Foo::Bar
的类型。 An object of type Foo::Bar
has an int
data member named a
, but a Foo
object itself doesn't have any Bar
or int
subobjects. 类型为
Foo::Bar
的对象具有名为a
的int
数据成员,但Foo
对象本身没有任何Bar
或int
子对象。
If you do want an object of type Bar
in every Foo
, you need to declare that member with some name: 如果你想在每个
Foo
中都想要一个Bar
类型的对象,你需要声明一个具有某个名称的成员:
class Foo
{
public :
struct Bar {
int a;
};
Bar bar;
};
This would let you do things like: 这可以让你做以下事情:
void test() {
Foo f;
f.bar.a = 5;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.