在不使用指针的情况下将数组作为C 中的参考传递

Passing array off as reference in c++ without using pointer

本文关键字:参考 指针 情况下 数组      更新时间:2023-10-16

我有一个关于C 必须完成的分配的快速问题。老师要求我包括以下功能:

void getPlayerInfo(Player &);
void showInfo(Player);
int getTotalPoints(Player [], int);

,但是我在第一个功能上工作遇到困难。...我不确定我是否正确调用了结构数组。有人可以看一下,看看我做错了什么吗?我有点摆弄它,我可以打电话给数组并将指针传递给数组,但老师要求"&"符号存在,所以我必须有另一种方法。请帮忙!谢谢

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
// Structure to hold information about a player
struct Player
{
    string name;        // to hold the players name
    int number;         // to hold players number
    int points;         // to hold the points scored by the player
};
// Function prototypes
void getPlayerInfo(Player &); // function to get the players information       from the user
void showInfo(Player);    // function to show the table
int main()
{
    const int numPlayers = 12;  // Constant to hold the number of players
    Player team[numPlayers];    // array to hold 12 structures
                            // Gather information about all 12 players
    getPlayerInfo(team);
    showInfo(team);

    return 0;
}
// Function to get the players info
void getPlayerInfo(Player& team)
{
   for (int count = 0; count < 12; count++)
{
    cout << "PLAYER #" << (count + 1) << endl;
    cout << "----------" << endl;
    cout << "Player name: ";
    cin.ignore();
    getline(cin, team[count].name);
    cout << "Player's number: ";
    cin >> team[count].number;
    cout << "Points scored: ";
    cin >> team[count].points;
    cout << endl;
}

}

getPlayerInfo()不接受数组,它接受对单个Player对象的引用。

您需要为数组中的每个播放器致电getPlayerInfo()。将循环移到getPlayerInfo()外,然后进入main()

您已经误解了这些功能的意图。

从您提供的信息中猜测,getPlayerInfo旨在获取个人 player的信息,而showPlayerInfo旨在显示个人 player的信息。

您正在尝试使用这些功能来做他们不打算做的事情,因此您很难弄清楚如何打电话以及如何实施它们是一件好事。

将这种经验视为需要收集的对象课程。