首页 > 解决方案 > 为什么我的 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() 函数中运行良好。

标签: c++

解决方案


问题在于如何将参数传递给函数:

void dispTeam(Team t1,Team t2);

这意味着Team对象是按传递的,这意味着函数内的局部参数变量将是原始对象的副本。然后,该函数将继续修改这些副本,这些副本独立于原始对象并且与原始对象不同。

您需要通过引用传递对原始对象的引用:

// Note ampersands here and here, meaning pass by reference
//                v        v
void dispTeam(Team& t1,Team& t2);

推荐阅读