I'm currently making a quick little text-based sports simulator. I have 2 classes so far, Team and 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:
crocovia.roster[0] // out of bounds access
Use std::vector
instead:
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.
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
roster = new Player[k];
, where k is the number of players you want in the team.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.