在不使用指针的情况下将数组作为C 中的参考传递
Passing array off as reference in c++ without using pointer
我有一个关于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的信息。
您正在尝试使用这些功能来做他们不打算做的事情,因此您很难弄清楚如何打电话以及如何实施它们是一件好事。
将这种经验视为需要收集的对象课程。
相关文章:
- 我可以有一个 ELI5 作为参考和指针以及何时使用它们吗?
- 类的方法和对象。参考?智能指针?简单的初始化?
- 我正在学习C++,我不能使用指针访问参考吗?(举个例子)
- 使用指针向量到参考向量是非法的吗?
- 函数参数绑定通过参考与传递指针传递数组的规则
- 参考参考static_cast的成本和指向指针static_cast的指针
- 函数采用原始指针试图通过错误msg中概述的参考来接受指针
- 为什么即使传递给函数作为参考,指针也未被分配
- 为什么通用参考概念不适用于函数指针的地图插入
- 是指代指针正交的参考文献
- 超载函数既不按值,也不是通过参考来对象,而是将撤销的指针换成对象
- 从参考中获取的指针可以在定义明确的C 中取无效
- 指针与参考示例,在什么情况下更好
- 为什么要拿参考的地址给我一个第二等级的指针
- 如何提升::序列化指针和参考
- 在范围外丢失指针参考
- 为什么动态演员只能与参考和指针一起使用
- 为什么该函数不会获得动态数组?(我正在使用指针和参考)
- 如果我创建一个模板类,而不是其他我将参考(指针)发送到该类的类
- 通过静态局部变量的参考/指针返回