Reputation: 365
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;
};
Upvotes: 1
Views: 1473
Reputation: 10726
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.
Upvotes: 3
Reputation: 117941
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
.
Upvotes: 1