c ++:使用main中定义的对象方法的函数

时间:2017-04-17 16:15:49

标签: c++ function oop object methods

早上好。 我和我的团队面临着c ++任务的问题。 在主要内容中,我们定义了一个名为Team的类的两个实例,“Team famous,Team fighters”。在main内部,我们调用了一个名为“团队细节”的函数;在该函数内部,我们试图访问我们刚创建的实例的公共方法(famous.getName)。将显示以下消息:

错误:请求'Famous'中的成员'getName',这是非类型'teamdetails():: team_t'

该消息涉及在下面的代码中可以看到的切换循环内的调用。我们无法找出问题的来源。 *在一个函数中使用'famous.getName'是一个问题,在这个函数中,'famous'对象没有被加入? * 注意:函数'teamdetails()'由函数'menu()'调用,由main调用。

感谢您的帮助!

#include "Player.h"
#include "Team.h"
using namespace std;

void teamdetails();

int main(){
   Team famous;
   Team fighters;
   cout<<"Welcome to the \"Survivor Experience of a lifetime\" !!!"<<endl;
   menu();
return 0;)

void teamdetails(){
   cout << " Which team are you interested in ? <famous/fighters>\t";
   enum team_t {famous = 0, fighters = 1};
   team_t   team_as_enum;  
   // cin >> team_as_enum;      // -> does not work.    Below I am trying
   //another alternative.

   string team;
   cin >>team;
   for(;;)
       if((team == "famous") || (team == "fighters"))
          break;

   if (team == "famous")
      team_as_enum = famous;
   else if(team == "fighters")
      team_as_enum = fighters;
   else
      cout<<"sth went wrong with your input";


   switch (team_as_enum){
      case famous: 
        cout<<"The name is"<< famous.getName() <<endl;
        cout<<"The number of players is "<<famous.getPlayers()<<endl;
        cout<<"Portions are "<<famous.getPortions()<<endl;
        cout<<"Victory : "<<famous.getVictories()<<endl;
        break;

      case fighters:  
        cout<<"The name is"<<fighters.getName()<<endl;
        cout<<"The number of players is "<<fighters.getPlayers()<<endl;
        cout<<"Portions are "<<fighters.getPortions()<<endl;
        cout<<"Victory : "<<fighters.getVictories()<<endl;
        break;
      default:
        cout<<"Ooop Entry not correct . Next time enter one of the following
        team's name <famous/fighters>"<<endl;
    }

    }

1 个答案:

答案 0 :(得分:0)

您可以通过声明famousteamdetails函数中重复使用enum team_t {famous = 0, fighters = 1};变量名称。选择一个不同的名字。类型famous的变量Team在该函数内部根本不可见,因为它在main函数范围内声明,您需要将其作为参数传递给teamdetails