如何引用嵌套结构?

时间:2012-02-23 06:43:58

标签: c++ struct nested

结构体中的struct,如何调用内部结构? 我目前的代码是

#include <iostream>
#include <string>

using namespace std;

int N_ITEMS;
int N_SEATS;

struct ST_SEATS{
struct ITM_TYPE {
   string name;
   float price;       
};
};

int main()
{
    cout << "Enter number of items: ";
    cin >> N_ITEMS;
    ST_SEATS seat[3];
    seat[1]::ITM_TYPE item[N_ITEMS];
    int i = 0;
    string name = "";
    string input;
    float price;
    while (i < N_ITEMS)
   {
      cout << "Input item name: ";
      cin >> input;
      item[i].name = input;
      cout << "item[" << i << "].name SET" << endl;
      cout << "Input item price: ";
      cin >> price;
      item[i].price = price;
      cout << "item[" << i << "].price SET" << endl;
      i++;
   }
   i = 0;
   while (i < N_ITEMS)
   {
      cout << "item[" << i << "].name = " << item[i].name << endl;
      cout << "item[" << i << "].price = " << item[i].price << endl;
      i++;
   }
   system("pause");
}

我正在尝试获得一个收据制造商计划,基本上每个座位都有自己的订单。 我知道这与问题没有关系,请求更多信息......哦,我几乎忘记添加的错误

21 E:\Documents\School\Computing\SDD\Assign#2\Projects\random.cpp `::ITM_TYPE' has not been declared 

21 E:\Documents\School\Computing\SDD\Assign#2\Projects\random.cpp expected `;' before "item" 

30 E:\Documents\School\Computing\SDD\Assign#2\Projects\random.cpp `item' undeclared (first use this function) 

3 个答案:

答案 0 :(得分:1)

使用此

ST_SEATS::ITM_TYPE st_seats;

答案 1 :(得分:1)

类型ITM_TYPE只存在一次,范围为ST_SEATSST_SEATS的每个实例都没有不同的类型。因此,定义数组的正确方法是

ST_SEATS::ITM_TYPE item[N_ITEMS];

但请注意,您的结构ST_SEATS实际上是空的(它不包含任何成员)。它只充当命名空间。因此,您应该用名称空间替换它:

namespace ST_SEATS
{
  struct ITM_TYPE
  {
    string name;
    float price;       
  };
}

好吧,我现在注意到你实际上定义了一个3 ST_SEATS的数组,但是根本没有使用该数组。我现在怀疑您可能希望将ITM_TYPE数组作为ST_SEATS成员。但在这种情况下,您必须直接在结构定义中声明这样的成员。

此外,我现在注意到您的数组大小是一个变量。这在C ++中是不可能的(虽然有些编译器将它作为本地数组的扩展)。因此,我现在认为你实际上想要的是:

#include <vector>

struct ST_SEATS{
  struct ITM_TYPE {
    string name;
    float price;       
  };
  std::vector<ITM_TYPE> items; // a vector is basically a dynamic array
};

int main()
{
  cout << "Enter number of items: ";
  cin >> N_ITEMS;
  ST_SEATS seat[3];
  seat[1].items.resize(N_ITEMS);
  std::string name = "";
  std::string input;
  float price;
  for (int i=0; i < N_ITEMS; ++i)
  {
    std::cout << "Input item name: ";
    std::cin >> input;
    seat[1].items[i].name = input;
    std::cout << "item[" << i << "].name SET" << std::endl;
    std::cout << "Input item price: ";
    std::cin >> price;
    seat[1].item[i].price = price;
    std::cout << "item[" << i << "].price SET" << std::endl;
  }

  for (int i=0; i < N_ITEMS; ++i)
  {
    std::cout << "item[" << i << "].name = " << seat[1].items[i].name << std::endl;
    std::cout << "item[" << i << "].price = " << seat[1].items[i].price << std::endl;
  }
  system("pause");
}

答案 2 :(得分:0)

seat[1]不是一种类型。访问内部类型槽ST_SEATS::ITM_TYPE

注意:启用C ++ 11功能后,您也可以说decltype(seat[1])::ITM_TYPE