Background:
I have created a player class and I want to ask the user how many players are going to play the game? Based on the user input I am trying to create that many instances of the player class. However, I used the following links to help me:
Create object using user input
http://www.cplusplus.com/forum/beginner/197342/
So, I tried their solution:
#include "Player.h"
int main() {
int totalPlayers = -1;
cout << "Enter total number of players: ";
while ((totalPlayers < 1) && (totalPlayers > 5)) {
cout << "How many players will be playing? (1-5): ";
cin >> totalPlayers;
}
vector<Player> players(totalPlayers);
system("pause");
}
I get the error: Unhandled exception at 0x763F40B2 in 16LinearChess.exe: Microsoft C++ exception: std::length_error at memory location 0x003BF690.
So, I googled this exact error and found this link: Error : std::length_error at memory location
So, firstly his code was no-where related to mine, but the error was same. I did not understand the answer, but I thought that I had to create the instances using heap memory. So I tried that:
#include "Player.h"
int main() {
int totalPlayers = -1;
cout << "Enter total number of players: ";
while ((totalPlayers < 1) && (totalPlayers > 5)) {
cout << "How many players will be playing? (1-5): ";
cin >> totalPlayers;
}
vector<Player> *players = new Player(totalPlayers);
delete[] players;
system("pause");
}
I got two errors:
Severity Code Description Project File Line Suppression State
Error (active) E0144 a value of type "Player *" cannot be used to initialize an entity of type "std::vector<Player, std::allocator> *" 16LinearChess D:\Keshav\Programming Languages\C++\Beginner\01 Michael Dawson\16LinearChess\LinearChess.cpp 64
Severity Code Description Project File Line Suppression State
Error (active) E0289 no instance of constructor "Player::Player" matches the argument list 16LinearChess D:\Keshav\Programming Languages\C++\Beginner\01 Michael Dawson\16LinearChess\LinearChess.cpp
This is my Player class:
#include <iostream>
class Player : public Board {
protected:
int m_position;
Log logger;
int m_playerNumber;
public:
static int m_numberOfPlayers;
Player() :m_position(0) {
++m_numberOfPlayers;
m_playerNumber = m_numberOfPlayers;
}
void m_SetPlayerPosition(int &position) {
if ((position < 0) || (position > 100)) {
m_position = 0;
logger.Error("Position cannot be less than or greater than 100. Your position has been reset to 0 because you fell out of the map.");
}
else {
m_position = position;
}
m_SetBoardPosition(m_position, m_numberOfPlayers); // update the position on the board.
}
friend ostream &operator << (ostream &os, Player &player) {
os << "Player position on board: " << player.m_position << "\nPlayer Number: " << player.m_playerNumber << '\n';
return os;
}
};
int Player::m_numberOfPlayers = 0; // initializing total number of players.
Thank You!