簡體   English   中英

了解嵌套結構

[英]Understanding Nested Structures

我目前正在開發需要嵌套結構的程序。 雖然,我不確定我是否理解。 如果有人可以的話,我想請您幫忙。 學習C ++的第一周,所以不要給我辛苦的時間:P

我應該創建一個包含兩個字符串成員(第一和最后一個)的Person結構。 創建一個包含四個字符串成員(街道,城市,州和郵政編碼)的地址結構。 並創建一個包含三個成員的嵌套結構Employee。 一個名為name的Person成員,一個名為homeAddress的Address成員和一個名為eid的int成員。

我認為我已經正確完成了大多數操作,但是由於某種原因,我的地址homeAddress下不允許使用不完整的類型。 另外,當它說創建嵌套結構“ Employee”時,是否意味着我必須在某個地方聲明Employee?

這是我到目前為止所擁有的,在此先感謝。

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

您的代碼幾乎完成了。 它應該是:

struct Person {
  string first;
  string last;
};

struct Address {
  string street;
  string city;
  string state;
  string zipcode;
};

struct Employee {
  Person name;
  Address homeAddress;
  int eid;
};

現在這里的誤稱是嵌套也可能意味着可見性或范圍。 因此,如果您想在Employee定義AddressPerson結構,則如下所示:

struct Employee {
  struct Address {
    //..
  };
  struct Employee {
    //..
  };
  Person name;
  Address homeAddress;
  int eid;
};

這樣,您就可以使“ PersonAddress的范圍僅PersonEmployee的范圍。

你很親密

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

請注意,最后一個struct在您描述時是“嵌套的”,因為它是一個struct ,其中包含的成員是另外兩種類型的struct

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM