[英]Understanding Nested Structures
I'm currently working on a program that requires a nested structure. 我目前正在开发需要嵌套结构的程序。 Though, I am not sure I understand it.
虽然,我不确定我是否理解。 I'd like your help with this if anyone could.
如果有人可以的话,我想请您帮忙。 First week learning C++ so don't give me a hard time :P
学习C ++的第一周,所以不要给我辛苦的时间:P
I'm supposed create a Person structure containing two string members, first and last. 我应该创建一个包含两个字符串成员(第一和最后一个)的Person结构。 Create an Address structure containing four string members, street, city, state, and zipcode.
创建一个包含四个字符串成员(街道,城市,州和邮政编码)的地址结构。 And also create a nested structure, Employee, that consists of three members.
并创建一个包含三个成员的嵌套结构Employee。 A Person member named name, an Address member named homeAddress and an int member named eid.
一个名为name的Person成员,一个名为homeAddress的Address成员和一个名为eid的int成员。
I think I've done most of it correctly, but I am getting an incomplete type is not allowed under my Address homeAddress for some reason. 我认为我已经正确完成了大多数操作,但是由于某种原因,我的地址homeAddress下不允许使用不完整的类型。 Also, when it says create a nested structure "Employee" does that mean I have to declare Employee somewhere?
另外,当它说创建嵌套结构“ Employee”时,是否意味着我必须在某个地方声明Employee?
Here is what I have so far, thanks in advance. 这是我到目前为止所拥有的,在此先感谢。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct Person {
string first;
string last;
};
struct Address {
string street;
string city;
string state;
string zipcode;
Person name;
Address homeAddress;
int eid;
};
Your code was almost complete. 您的代码几乎完成了。 It should be:
它应该是:
struct Person {
string first;
string last;
};
struct Address {
string street;
string city;
string state;
string zipcode;
};
struct Employee {
Person name;
Address homeAddress;
int eid;
};
Now the misnomer here is that nested can also imply visibility or scope. 现在这里的误称是嵌套也可能意味着可见性或范围。 Hence, if you wanted to define the structure
Address
and Person
within Employee
, it would look like this: 因此,如果您想在
Employee
定义Address
和Person
结构,则如下所示:
struct Employee {
struct Address {
//..
};
struct Employee {
//..
};
Person name;
Address homeAddress;
int eid;
};
That way, you make the scope of Person
and Address
native to that of Employee
alone. 这样,您就可以使“
Person
和Address
的范围仅Person
“ Employee
的范围。
You are very close 你很亲密
struct Person {
string first;
string last;
};
struct Address {
string street;
string city;
string state;
string zipcode;
};
struct Employee {
Person name; // instance of Person struct from above
Address homeAddress; // instance of Address struct from above
int eid;
};
Note that this last struct
is "nested" as you describe it, since it is a struct
that contains members that are two other types of struct
. 请注意,最后一个
struct
在您描述时是“嵌套的”,因为它是一个struct
,其中包含的成员是另外两种类型的struct
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.