-2

你好我有三个班

  1. 抽象足球队
  2. 球员足球队
  3. PlayersFieldPlayerStates

PlayerSoccerTeam 是 AbstSoccerTeam 的子类。

bool AlanSoccerTeam::isClosestTeamMemberToSupportingPlayer(FieldPlayer* plyr)

是球员足球队的一种方法。

我试图用这个在 PlayersFieldPlayerStates 类中调用该方法

PlayersSoccerTeam* sTeam;
sTeam->isClosestTeamMemberToSupportingPlayer(player);

我运行它时会遇到这个问题

使用了未初始化的局部变量“sTeam”

我不知道发生了什么或为什么我收到此错误。

非常感谢您的帮助

4

2 回答 2

1

The problem is you have created a pointer to a PlayersSoccerTeam but you have not actually created the object itself yet.

I would suggest doing this.

PlayersSoccerTeam sTeam;
sTeam.isClosestTeamMemberToSupportingPlayer(player);

You could alternatively do this.

PlayersSoccerTeam* sTeam = new PlayersSoccerTeam()
sTeam->isClosestTeamMemberToSupportingPlayer(player);

As perhaps an interesting education experience create a constructor that prints something to stdout when it is run and then try doing these two options and yours to see what happens. A constructor will be run whenever a new object is created.

于 2013-03-04T18:37:26.630 回答
1
PlayersSoccerTeam* sTeam;

这一行声明了一个指向 a 的指针,仅此PlayersSoccerTeam而已。你从这一行得到的只是一个指针。由于您尚未初始化,因此它没有特别指向任何地方。没有PlayersSoccerTeam任何地方可以指向。

如果你想要一个类型的对象PlayersSoccerTeam,那么你只想要:

PlayersSoccerTeam sTeam;
sTeam.isClosestTeamMemberToSupportingPlayer(player);

由于您告诉我们您的层次结构,因此您可能希望将您的PlayersSoccerTeam多态用作AbstSoccerTeam. 在这种情况下,您将需要使用指针或引用。这可以这样做:

AbstSoccerTeam* sTeam = new PlayersSoccerTeam();
// ...
delete sTeam;

请注意,这仍然只声明了一个指针,但该表达式new PlayersSoccerTeam还创建了一个PlayersSoccerTeam指针指向的对象。请注意,将指向 aPlayersSoccerTeam的指针分配给指向其父级的指针是完全可以的AbstSoccerTeam——这就是多态性。如果你这样做,你必须确保你delete sTeam;以后,否则对象将被泄露。

处理动态分配对象的用户的一种更安全的方法是使用智能指针,您可以这样做:

std::unique_ptr<AbstSoccerTeam> sTeam(new PlayersSoccerTeam());

现在您将不必这样做delete,因为它std::unique_ptr会为您处理。

于 2013-03-04T18:36:44.273 回答