c++ - 为什么我的 cout 没有在输出中显示字符串?
问题描述
#include <iostream>
#include <string>
using namespace std;
class Team {
public:
string teamName ;
string playerOne ;
string PlayerTwo ;
string playerThree ;
double totalRunsScored;
};
void welcomeMessage();
void dispTeam(Team t1,Team t2);
void roleSelection(Team t1,Team t2);
int currentBatsmen;
int currentBowler;
int main()
{
welcomeMessage();
Team t1,t2 ;
dispTeam(t1,t2);
cout<<"\n lets start first innings \n";
roleSelection(t1,t2);
return 0;
}
void welcomeMessage(){
cout << "Welcome to gully Cricket \n";
cout<< "\n";
cout<< "\n";
cout<< "\n";
cout << "Enter the name of your team players for Team one and Two\n ";
}
void dispTeam(Team t1,Team t2) {
getline(cin,t1.playerOne);
getline(cin,t1.PlayerTwo);
getline(cin,t1.playerThree);
cout << "\n Team one \t" <<"\t" <<t1.playerOne << "\t" << t1.PlayerTwo << "\t" << t1.playerThree <<"\t" << endl ;
getline(cin,t2.playerOne);
getline(cin,t2.PlayerTwo);
getline(cin,t2.playerThree);
cout << "\n Team Second \t" << "\t" <<t2.playerOne <<"\t"<< t2.PlayerTwo <<"\t"<< t2.playerThree <<"\t" << endl ;
}
void roleSelection(Team a,Team b){
cout<<"Choose Your batsmen from Team one press 1,2,3 : \n";
cin >> currentBatsmen;
if (currentBatsmen==1){
cout<<a.playerOne;
}else if (currentBatsmen==2){
cout<<"you have chosen \t" << a.PlayerTwo <<" \t as your batsmen";
}else if(currentBatsmen==3){
cout<<"you have chosen \t "<< a.playerThree <<" \t as your batsmen";
}
}
在这个函数角色选择()中,我的 cout 显示为空白,我无法理解为什么?上面你可以看到我的代码,我也包含了字符串头文件和 iostream。它在 dispTeam() 函数中运行良好。
解决方案
问题在于如何将参数传递给函数:
void dispTeam(Team t1,Team t2);
这意味着Team
对象是按值传递的,这意味着函数内的局部参数变量将是原始对象的副本。然后,该函数将继续修改这些副本,这些副本独立于原始对象并且与原始对象不同。
您需要通过引用传递对原始对象的引用:
// Note ampersands here and here, meaning pass by reference
// v v
void dispTeam(Team& t1,Team& t2);
推荐阅读
- c# - 从 EF4 升级到 EF6 后实体框架速度变慢 (EntityFramework.6.2.0)
- javascript - 将 django 表单中的两个字段相乘并用结果填充第三个字段
- bash - 从网站获取变量,然后存储
- c++ - 为什么指针没有隐式转换成
常量*常量 - docker - Google Compute Engine 上的 Docker - 如何以正确的权限挂载主机目录
- google-apps-script - 如何将数据从表格发送到弹出窗口
- android - Android 形状:带刻度线的圆圈
- python - DNS 标头作为原始数据与 scapy 一起发送
- r - 使用 lapply 后矩阵转换为列表。不打算
- java - 如何在 Spring 反应式处理程序函数中提取请求正文?