简体   繁体   English

简单运动仿真中的分割错误

[英]Segmentation Fault in simple Sports Simulation

I'm currently making a quick little text-based sports simulator. 我目前正在制作一个快速的基于文本的小型体育模拟器。 I have 2 classes so far, Team and Player. 到目前为止,我有2个班级,分别是Team和Player。 I tried making an array of Players in a team, aka a roster. 我试图在一个团队(又名册)中安排一组球员。 (Not sure how to do it otherwise). (不知道如何做否则)。 I tried making a player and then assigning him to the first place in the roster array. 我试着建立一个球员,然后将他分配到花名册阵列中的第一位。 It compiles fine, but when I run the program, I get the 'segmentation fault' error, which has to do with an error in memory that I've cause, I believe. 它可以很好地编译,但是我运行该程序时会遇到“分段错误”错误,我认为这与我引起的内存错误有关。 The code might not be the best, so sorry if my code isn't the most optimized. 该代码可能不是最好的,如果我的代码不是最优化的,请对不起。 If you have any suggestions on how I can fix this, let me know. 如果您对如何解决此问题有任何建议,请告诉我。 Thanks. 谢谢。

#include <iostream>
#include <string>
#include <stdio.h>
#include <vector>

using namespace std;

class Player {
  public:
    string playerName;
    string playerAge;
    string position;
} players;

 class Team: public Player {
  public:
     string name;
     Player roster[];
 } teams;

 void teamCrocovia() {
     Team crocovia;
     crocovia.name = "ComArch Crocovia";
     Player cro1;
     crocovia.roster[0] = cro1; // This is the segmentation fault.
 }

 int main() {
     teamCrocovia();
     return 0;
 }

You cannot expect this: 您不能期望这样:

Player roster[];                 // this is a zero-sized array

to be a variable-sized array (no such thing in C++) and add elements like: 成为一个可变大小的数组(C ++中没有这种东西),并添加以下元素:

crocovia.roster[0]               // out of bounds access

Use std::vector instead: 使用std::vector代替:

std::vector<Player> roster;      // in Team
crocovia.roster.push_back(cro1); // add player

Also, I don't get why Team inherits from Player and you're immediately creating objects with plural names of each class, that are not even used. 另外,我不明白为什么TeamPlayer继承,而您立即使用每个类的复数名称创建对象,甚至没有使用过。

You should define the size of the array, for example 您应该定义数组的大小,例如

Player roster[5];

If when you're writing the code you don't know for sure the size of the array, you should just declare it as 如果在编写代码时不确定数组的大小,则应将其声明为

Player *roster;

and somewhere else (preferably in the constructor of class Team) actually make it an array, maybe like this 在其他地方(最好是在Team类的构造函数中)实际上使它成为一个数组,也许像这样

roster = new Player[k];

, where k is the number of players you want in the team. ,其中k是您要加入团队的人数。

Also, about this 另外,关于这个

 class Team: public Player

I don't think that is what you want. 我认为那不是你想要的。 I dont think you want to declare that Team IS A Player. 我不认为您想宣布团队是一名球员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM