C ++打印在main中声明的数组的内容

时间:2016-05-01 01:05:12

标签: c++ arrays class io

处理必须在main中声明数组的程序(在本例中为distList[5]),并且必须将其发送到一个必须由用户输入填充的成员({{1} })然后发送到另一个成员(inputDist)进行打印和添加,如名称所示。我相信我已经填满了阵列,但我不确定如何从那里开始。任何帮助表示赞赏。

printAndAdd

此外,这是CDistance的类定义:

void CDistance::inputDist(CDistance distList[], int size)
{

    for (int i = 0; i < 1; i++)
    {
        cout << "Please enter 5 digits following each one with a space to place into the array: " << endl;
        int ui1;    cin >> ui1;
        int ui2;    cin >> ui2;
        int ui3;    cin >> ui3;
        int ui4;    cin >> ui4;
        int ui5;    cin >> ui5;
        distList[i] = CDistance(ui1, ui2, ui3, ui4, ui5);
        cout << distList;

    }
}

void CDistance::printAndAdd(const CDistance distList[], int size)
{
    //cout << distList;
}

int main()
{
    CDistance distList[5];

    CDistance d1, d2(0, 0, 0, 0, 0);

    d1.setDistt();
    d1.printDistt();
    d1.menu(d2);
    d1.inputDist(distList, 5);
    d1.printAndAdd(distList, 5);
    _getch();
    return 0;
}

1 个答案:

答案 0 :(得分:1)

在评论中,你说:

  

我该怎么做?当我尝试使用for循环,尝试打印内容时,它会给我错误&#34;没有操作符&#39;&lt;&lt;&lt;&#匹配这些操作数。&#34;我确实尝试创建&lt;&lt;&lt;&lt;&lt;但不确定如何执行它。

声明operator>>operator<<重载,以便您从流中读取CDistance并将CDistance写入流。

class CDistance;
std::istream& operator>>(std::istream& is, CDistance& distance);
std::ostream& operator<<(std::ostream& os, CDistance const& distance);

让他们成为班级的friend

class CDistance
{

   ...

   friend std::istream& operator>>(std::istream& is, CDistance& distance);
   friend std::ostream& operator<<(std::ostream& os, CDistance const& distance);

};

实施它们。

std::istream& operator>>(std::istream& is, CDistance& d)
{
   return (is >> d.feet >> d.inches >> d.feet2 >> d.inches2 >> d.five);
}

std::ostream& operator<<(std::ostream& os, CDistance const& distance);
{
   // Add a space between the members when writing it out.
   return (is << d.feet << " " << d.inches << " "
              << d.feet2 << " " << d.inches2 << " " << d.five);
}

现在你可以使用

Distance d;
std::cin >> d;
std::cout << d << std::endl;

我建议进行以下额外改进:

您不需要inputDistprintAndAdd成为班级的会员功能,因为他们不需要访问班级的private成员。它们可以是非成员函数。

void inputDist(CDistance distList[], int size)
{
   // for (int i = 0; i < 1; i++)
   for (int i = 0; i < size; i++) // Use size, not 1
   {
      cout << "Please enter 5 digits following each one with a space to place into the array: " << endl;
      cin >> distList[i];
      cout << distList << endl;
   }
}

void printAndAdd(const CDistance distList[], int size)
{
   for (int i = 0; i < size; i++)
   {
      cout << distList[i] << std::endl;
      // Not sure what "Add" means to you.
   }
}