我目前在使用对象和类时遇到一些困难。我正在创建对象,在这种情况下,足球运动员在一个类的一个功能中,然后尝试在另一个功能中显示他们的细节。 这是创建对象的函数,
void create_all_players(){
Midfielder *midfielder1= new Midfielder("Jordan Lewis");
Midfielder *midfielder2= new Midfielder("David Armitage");
Midfielder *midfielder3= new Midfielder("Tom Rockliff");
Midfielder *midfielder4= new Midfielder("Gary Ablett");
Midfielder *midfielder5= new Midfielder("Dyson Heppel");
Midfielder *midfielder6= new Midfielder("Scott Pendlebury");
Midfielder *midfielder7= new Midfielder("Michael Barlow");
Midfielder *midfielder8= new Midfielder("Jack Steven");
}
这是我试图输出玩家详细信息的功能,
void display_all_players(){
cout<<midfielder1->Player_Details()<<endl;
cout<<midfielder2->Player_Details()<<endl;
cout<<midfielder3->Player_Details()<<endl;
cout<<midfielder4->Player_Details()<<endl;
cout<<midfielder5->Player_Details()<<endl;
cout<<midfielder6->Player_Details()<<endl;
cout<<midfielder7->Player_Details()<<endl;
cout<<midfielder8->Player_Details()<<endl;
}
但是当我尝试运行程序时我得到了错误,'midfielder1'没有在这个范围内声明,对于所有对象。如何在display_all_players函数中没有错误的情况下引用对象? 如果需要其他信息,中场是从下面的球员类继承的类。
Player.h
#ifndef PLAYER_H
#define PLAYER_H
#include <string>
class Player
{
public:
Player();
Player(std::string);
std::string Name;
std::string Get_Name();
virtual std::string Player_Details();
};
#endif // PLAYER_H
Player.cpp
#include "Player.h"
#include <iostream>
#include <string>
#include <sstream>
#include "Player.h"
#include "Midfielder.h"
using namespace std;
Player::Player():Name("Default"){}
Player::Player(string Name){
this->Name=Name;
}
string Player::Player_Details(){
return "Player : " + this->Name ;
}
Midfielder.h
#ifndef MIDFIELDER_H
#define MIDFIELDER_H
#include "Player.h"
class Midfielder : public Player
{
public:
Midfielder();
Midfielder(std::string);
virtual std::string Player_Details();
};
#endif // MIDFIELDER_H
和Midfielder.cpp
#include <iostream>
#include <string>
#include "Player.h"
#include "Midfielder.h"
using namespace std;
Midfielder::Midfielder(){}
Midfielder::Midfielder(string Name){
this->Name=Name;
}
string Midfielder::Player_Details(){
return "Midfielder : " + this->Name;
}
}
感谢您提前提供任何帮助
答案 0 :(得分:0)
您在midfielder
方法中创建了create_all_players
个变量。这使它们具有功能范围,并且只能从那里访问它们。你需要将中场变量存储在其他地方,比如全局(在任何函数之外)。