Understanding Nested Structures

ⅰ亾dé卋堺 提交于 2019-12-13 00:06:15

问题


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

I'm supposed create a Person structure containing two string members, first and last. 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. A Person member named name, an Address member named homeAddress and an int member named eid.

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. Also, when it says create a nested structure "Employee" does that mean I have to declare Employee somewhere?

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

回答1:


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:

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.




回答2:


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.



来源:https://stackoverflow.com/questions/25457275/understanding-nested-structures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!