(The issue has been solved and the solution has been added as comment line to main.cpp)
The problem I'm having is described in the main.cpp file. I already checked another questions about this and none of them really helped.
I'm trying to create a console application with C++ where you can add BOOKS to the LIBRARY. In the library class, there is a displayInfo() function which displays the info of a particular book. It can display integer or double valued informations without having a problem however it is having a trouble when I try to display string typed informations. It just prints blank. Let me give you a little sample of my code.
Here is Book.h
#ifndef BOOK_H
#define BOOK_H
#include <string>
class Book
{
friend class Library;
public:
void setName();
std::string getName();
private:
std::string nameOfBook;
};
#endif
Book.cpp
#include "Book.h"
#include <iostream>
#include <string>
using namespace std;
void Book::setName()
{
string nameOfBook;
cout << "Please enter the name of the book: ";
cin >> nameOfBook;
this->nameOfBook = nameOfBook;
}
string Book::getName()
{
return nameOfBook;
}
Library.h
#ifndef LIBRARY_H
#define LIBRARY_H
#include "Book.h"
#include <array>
class Library
{
private:
std::array <Book , 10> bookArray; // I have to use this
public:
void addBook();
void displayInfo();
};
#endif
Library.cpp
#include "Library.h"
#include "Book.h"
#include <iostream>
#include <string>
#include <array>
using namespace std;
void Library::addBook()
{
bookArray[0].setName();
}
void Library::displayInfo()
{
cout << "The book: " << bookArray[0].getName() << endl;
}
And main.cpp
#include <iostream>
#include "Book.h"
#include "Library.h"
#include <string>
#include <array>
using namespace std;
int main()
{
// The problem is solved
// Create the objects out of the loop
// Library obj1 <---- this solved it
while (true)
{
int number; // Ask user what to do
cout << "Press 1 to add a book\n"
<< "Press 2 to display info\n"
<< "Press 0 to quit\n";
cin >> number;
if (number == 1) // Add a book
{
Library obj1; // <------ THIS IS WRONG
obj1.addBook(); // Consider we named the book as 'Fly'
}
else if (number == 2)
{
Library obj1; // <------ THIS IS WRONG
obj1.displayInfo(); // ******* The output I'm expecting is The Book: Fly
// But instead, it only gives me The Book:
// I have 4 more strings like this in the main project and all of them have the same problem
}
else if (number == 0) // Everything else
{
break;
}
else
{
cout << "Wrong input\n";
continue;
}
}
}
Edit:
I coded this with VS Code and compiled it with MinGW (8.2.0) if it matters.
one problem in your code is that you have many instances of a library class so addBook is landing in one object and displayInfo in a new one (empty one)
you have to:
int main()
{
Library obj1; // declare the lib in scope for all the cases
while (true)
{
int number; // Ask user what to do
cout << "Press 1 to add a book\n"
<< "Press 2 to display info\n"
<< "Press 0 to quit\n";
cin >> number;
if (number == 1) // Add a book
{
obj1.addBook(); // Consider we named the book as 'Fly'
}
else if (number == 2)
{
//Library obj1;
obj1.displayInfo(); // ******* The output I'm expecting is The Book: Fly
// But instead, it only gives me The Book:
// I have 4 more strings like this in the main project and all of them have the same problem
}
else if (number == 0) // Everything else
{
break;
}
else
{
cout << "Wrong input\n";
continue;
}
}
}
u are creating the object again in every iteration of the loop. therefore overwriting the old object that has been given a name.
Related
This question already has answers here:
Why can templates only be implemented in the header file?
(17 answers)
Closed 11 months ago.
This is basically two errors in one, that seem to come from the same thing. If I define my functions in my main.cpp file, and forward declare them at the top of the file, it doesn't give me any errors and everything runs smoothly.
When trying to declutter and move things into seperate .cpp files, it starts to give me linker errors and saying things are undefined even though I am using appropriate header files. The code is shown below:
main.cpp
#include "io.h"
#include <iostream>
#include <map>
class exchangeRates;
void menu();
int main()
{
menu();
return EXIT_SUCCESS;
}
// class storing exchange rates
class exchangeRates
{
public: // Access specifier
// Data Members
std::map<std::string, double> usd = {
{"GBP", 1.2},
{"EUR", 0.7},
};
std::map<std::string, double> gbp = {
{"USD", 0.9},
{"EUR", 1.4},
};
};
// menu function
void menu()
{
// get reference currency code from user
std::string refCurrency{ obtainCodeFromUser() };
// create 'rates' instance of 'exchangeRates' class
exchangeRates rates{};
// print the exchange values for that currency
if (refCurrency == "USD")
{
printExchangeValues(rates.usd, refCurrency);
}
else if (refCurrency == "GBP")
{
printExchangeValues(rates.gbp, refCurrency);
}
else
{
std::cout << "\nInvalid currency code. Example: USD, GBP, EUR etc.\n\n";
menu();
}
}
io.h
#ifndef IO_H
#define IO_H
#include <iostream>
#include <map>
std::string obtainCodeFromUser();
double obtainAmountFromUser();
template<typename Map>
void printExchangeValues(Map& valuedCurrencies, std::string refCurrency);
#endif
io.cpp
#include "io.h"
#include <iostream>
#include <map>
// io functions for currency converter
std::string obtainCodeFromUser()
{
// obatin reference currency code from user
std::cout << "Enter currency code for reference currency (case-sensitive): ";
std::cin.clear();
std::string refCurrency{};
std::cin >> refCurrency;
std::cin.ignore(INT_MAX, '\n');
return refCurrency;
}
double obtainAmountFromUser()
{
// obtain amount of currency to be converted from user
std::cout << "Enter amount of currency to convert: ";
std::cin.clear();
double amount{};
std::cin >> amount;
std::cin.ignore(INT_MAX, '\n');
return amount;
}
template<typename Map>
void printExchangeValues(Map& valuedCurrencies, std::string refCurrency)
{
// obtain amount of currency to be converted
double amount{ obtainAmountFromUser() };
std::cout << refCurrency << " " << amount << " is worth:\n";
for (auto& item : valuedCurrencies) {
std::cout << item.first << ": " << amount * item.second << '\n';
}
}
I am still a beginner with C++ so some parts have been copied from other open-source programs, and I know there are probably plenty of places to improve my code, but I'm mainly interested in why it just won't compile. The examples I followed when learning how to use header files worked fine and I don't believe I've done anything different here.
It says the identifiers "obtainCodeFromUser" and "printExchangeValues" are undefined.
The linker error it gives is LNK2019 'unresolved external symbol ...' and it seems to be relating to the printExchangeValues function.
Any help is massively appreciated!
The issue mentioned by WhozCraig is very useful, I hope you will read it carefully. Regarding your question, after I modified some code, the program can run correctly. The error is caused by the template. Since you are a beginner and the program is not very complicated, the following code is more convenient for you to understand:
main.cpp
#include "io.h"
#include <iostream>
#include <map>
// class storing exchange rates
class exchangeRates
{
public: // Access specifier
// Data Members
std::map<std::string, double> usd = {
{"GBP", 1.2},
{"EUR", 0.7},
};
std::map<std::string, double> gbp = {
{"USD", 0.9},
{"EUR", 1.4},
};
};
template<typename Map>
void printExchangeValues(Map& valuedCurrencies, std::string refCurrency)
{
// obtain amount of currency to be converted
double amount{ obtainAmountFromUser() };
std::cout << refCurrency << " " << amount << " is worth:\n";
for (auto& item : valuedCurrencies) {
std::cout << item.first << ": " << amount * item.second << '\n';
}
}
// menu function
void menu()
{
// get reference currency code from user
std::string refCurrency{ obtainCodeFromUser() };
// create 'rates' instance of 'exchangeRates' class
exchangeRates rates{};
// print the exchange values for that currency
if (refCurrency == "USD")
{
printExchangeValues(rates.usd, refCurrency);
}
else if (refCurrency == "GBP")
{
printExchangeValues(rates.gbp, refCurrency);
}
else
{
std::cout << "\nInvalid currency code. Example: USD, GBP, EUR etc.\n\n";
menu();
}
}
int main()
{
menu();
return EXIT_SUCCESS;
}
io.h
#ifndef IO_H
#define IO_H
#include <iostream>
#include <map>
std::string obtainCodeFromUser();
double obtainAmountFromUser();
#endif
io.cpp
#include "io.h"
#include <iostream>
#include <map>
// io functions for currency converter
std::string obtainCodeFromUser()
{
// obatin reference currency code from user
std::cout << "Enter currency code for reference currency (case-sensitive): ";
std::cin.clear();
std::string refCurrency{};
std::cin >> refCurrency;
std::cin.ignore(INT_MAX, '\n');
return refCurrency;
}
double obtainAmountFromUser()
{
// obtain amount of currency to be converted from user
std::cout << "Enter amount of currency to convert: ";
std::cin.clear();
double amount{};
std::cin >> amount;
std::cin.ignore(INT_MAX, '\n');
return amount;
}
I've got the bare shell of a program with a "BasicObject" class and a randum number generator class implemented. When I run the program, the console closes immediately, and cin functions, system("pause"), etc. have no effect. I suspect a crash, but can't find what the source might be. Any help?
BaseObject.cpp:
#include "BaseObject.h"
#include "RandNumGenerator.h"
#include <iostream>
#include <string>
using namespace std;
BaseObject::BaseObject() {
RandNumGenerator* numGen;
set_id(numGen->generate_randNum_str(5));
delete numGen;
}
BaseObject::~BaseObject() {}
...
//void - sets value of string "id"
void BaseObject::set_id(string newId) {
id = newId;
}
Here's the main function:
#include <iostream>
#include <string>
#include "BaseObject.h"
using namespace std;
int main() {
string userIn = "";
BaseObject* obj;
while (userIn != "q") {
cout << "Id of \"obj\" is " << obj->get_id() << endl;
cout << endl << "Type 'q' to quit." << endl;
cin >> userIn;
}
return 0;
}
Your obj object is not instantiated....
It's crashing, because here
obj->get_id()
obj is not initializated yet. Just a pointer to memory with some random garbage.
You need something like
BaseObject* obj = new BaseObject()
Before you can use obj
I have a banking project and I am trying to set up the bank name, address, and working hours. My getlines are showing an error as well as my get functions.
Input exact error messages here please.
'getline': no matching overloaded function found
no suitable user-defined conversion from "Bank" to "std::string" exists
Here's the class for bank:
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cctype>
#include <cstdlib>
using namespace std;
class Bank {
public:
void setBankName(string bn) { bn = bankname; }
string getBankName() { return bankname; }
void setBankAdd(string ba) { ba = bankadd; }
string getBankAdd() { return bankadd; }
void setWorkingHours(string bwh) { bwh = bankworkinghours; };
string getWorkingHours() { return bankworkinghours; }
private:
string bankname, bankadd, bankworkinghours;
};
//and then this is in my main function
int main() {
Bank bankname, bankadd, bankworkinghours;
char userChoice; // numbers 1-9
int number=0;
system ("color 5f");
cout << "Name of bank: ";
getline(cin, bankname); **//all the get lines also show error**
cout << endl;
cout << "Bank address: ";
getline(cin, bankadd);
cout << endl;
cout << "Bank working hours: ";
getline(cin, bankworkinghours);
cout << endl;
bankname.setBankName(bankname); //the things in the parentheses show error
bankadd.setBankAdd(bankadd);
bankworkinghours.setWorkingHours(bankworkinghours);
The error is self explanatory. 2nd parameter of getline function is std:string so define bankname as std:string and then set the name of bank object by setBankName.
1- You did not created bank Object in the main to set class attributes.
You need an Object with reference to that object you will set the parameters of the class bank.
2- bankname, bankadd, bankworkinghours are string and you made them Bank
Here is updated code and working fine in VS 2019 without any error. Just a few changes in the first 2 and last three lines of main
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cctype>
#include <cstdlib>
using namespace std;
class Bank {
public:
void setBankName(string bn) { bn = bankname; }
string getBankName() { return bankname; }
void setBankAdd(string ba) { ba = bankadd; }
string getBankAdd() { return bankadd; }
void setWorkingHours(string bwh) { bwh = bankworkinghours; };
string getWorkingHours() { return bankworkinghours; }
private:
string bankname, bankadd, bankworkinghours;
};
//and then this is in my main function
int main() {
Bank bankObj;
string bankname, bankadd, bankworkinghours;
char userChoice; // numbers 1-9
int number = 0;
system("color 5f");
cout << "Name of bank: ";
getline(cin, bankname);
cout << endl;
cout << "Bank address: ";
getline(cin, bankadd);
cout << endl;
cout << "Bank working hours: ";
getline(cin, bankworkinghours);
cout << endl;
bankObj.setBankName(bankname);
bankObj.setBankAdd(bankadd);
bankObj.setWorkingHours(bankworkinghours);
}
void setBankName(string bn) { bn = bankname; } is the wrong way around. try bankname = bn.
I'm working on C++, and this is just a very basic program, but I'm still getting an error.
The error message is:
'class secondary' has no member named 'getting'.
Why is this? It works for my void setting, but not for getting? What am I doing wrong here?
main.cpp
#include <iostream>
#include <string>
#include "secondary.h"
using namespace std;
int main(){
secondary s;
int scale;
cout << "On a scale of 1-10, how awesome are you?" << endl;
cin >> scale;
cout << endl;
s.setting(scale);
cout << s.getting();
return 0;
}
secondary.h
#ifndef SECONDARY_H
#define SECONDARY_H
#include <string>
class secondary
{
public:
void setting(int x);
string getting();
};
#endif // SECONDARY_H
secondary.cpp
#include "secondary.h"
#include <iostream>
#include <string>
using namespace std;
void secondary::setting(int x){
factor = x;
}
string secondary::getting(){
string result;
if(factor < 3){
result = "You have a very low self esteem.";
}elseif(factor > 3){
if(factor > 7){
result = "You have a very high self esteem."
}else{
result = "You have a medium self esteem."
}
}
return result;
}
private factor;
Actually, looking at this again, and deeper, this code has many issues (semicolons missing at key points and the private int definition should have been in the header file, not the cpp file 9t(private is its own section, see below):The problem, from what I can see, s has not yet been instantiated yet, do so and the operation should work correctly.
Please also note that when factor was defined in the cpp file, it was defined at bottom, it should actually be defined before any use of the variable to be defined (in the header file is better meet with common/conventional coding standards).
Please check this tested code:
main.cpp
#include <iostream>
#include <string>
#include "secondary.h"
using namespace std;
int main(){
secondary s;
int scale;
cout << "On a scale of 1-10, how awesome are you?" << endl;
cin >> scale;
cout << endl;
s.setting(scale);
cout << s.getting();
return 0;
}
secondary.h
#ifndef SECONDARY_H
#define SECONDARY_H
#include <string>
class secondary
{
public:
void setting(int x);
std::string getting();
private: // Note: this is how you do private
int factor; // This is the definition with type int, missing in original
};
#endif // SECONDARY_H
secondary.cpp
#include "secondary.h"
#include <iostream>
#include <string>
using namespace std;
void secondary::setting(int x){
factor = x;
}
string secondary::getting(){
string result;
if (factor < 3){
result = "You have a very low self esteem.";
}else if(factor > 3){
if (factor > 7){
result = "You have a very high self esteem.";
}
else{
result = "You have a medium self esteem.";
}
}
return result;
}
I know this problem is assessed many times on these forums, but they really are unique to their specific cases most times.
This is a project for a class (on C++ no less), and the point of the project was to remake the classic board game Reversi.
I have toiled through code for hours and finally made a program that will work, or so I thought!
The big problem I am having seems to come from my deconstructor as it's giving me this error many of us have seen. My code is posted below and from my own debugging code (using helpful cout messages) I have determined that the program manages to run to the end of the the Game.cpp class. Only, it stumbles on the deconstructor and crashes before finally "ending nicely".
Board.h
#include <iostream>
#include <cstdlib>
#include <vector>
#ifndef BOARD_H
#define BOARD_H
using namespace std;
enum Piece {LIGHT, DARK, EMPTY, BORDER};
typedef int Move;
Move const NullMove = -1;
int const MAX_SQUARES = 100;
enum Direction {N=0, NE=1, E=2, SE=3, S=4, SW=5, W=6, NW=7};
class Board
{
public:
Board();
void reset();
void display();
void makeMove(Piece, Move);
bool isLegal(Piece, Move);
Piece getWinner();
Piece getPlayer();
void genMoves();
int numMoves();
Move getMove(int) const;
bool gameOver;
private:
Piece board[MAX_SQUARES];
int lightPieces;
int darkPieces;
vector<Move> goodMoves;
static Piece currentPlayer;
vector <int> offset;
};
#endif
Board.cpp
#include <iostream>
#include <cstdlib>
#include <vector>
#include "Board.h"
using namespace std;
Board::Board()
{
reset();
for(int i=0;i<MAX_SQUARES;++i)
{
if(i<11 || i>88 || i%10==0 || i%10==9)
board[i]=BORDER;
}
offset.push_back(10);
offset.push_back(11);
offset.push_back(1);
offset.push_back(-9);
offset.push_back(-10);
offset.push_back(-11);
offset.push_back(-1);
offset.push_back(9);
board[44] = LIGHT;
board[45] = DARK;
board[54] = DARK;
board[55] = LIGHT;
gameOver=false;
}
void Board::reset()
{
for(int i=0; i<MAX_SQUARES;++i)
board[i] = EMPTY;
}
void Board::display()
{
for(int i=0;i<MAX_SQUARES;++i)
{
switch(board[i])
{
case LIGHT:
cout << "|LG|";
break;
case DARK:
cout << "|DR|";
break;
case EMPTY:
cout << "| |";
break;
case BORDER:
if(i<9)
cout << "<0" << i << ">";
else if(i==9)
cout << "<09>\n----------------------------------------\n";
else if(i%10==9)
cout << "<$$>\n----------------------------------------\n";
else if(i%10==0)
cout << "<" << i << ">";
else if(i<11 || i>90)
cout << "<$$>";
break;
}
}
}
void Board::makeMove(Piece p, Move m)
{
genMoves(); //generate valid moves
cout << "generated moves\n";
int good = numMoves(); //gets number of moves
if(good>0) //if there are valid moves
{
cout << "more than 0\n";
for(int i=0;i<goodMoves.size();++i) //checking the valid move list
{
if(m==goodMoves[i]) //if our move is in the list
{
cout << "move was in list\n";
board[m]=p; //change square
if(board[m]==DARK)
cout << "ITS DARK\n";
else if(board[m]==LIGHT)
cout << "ITS LIGHT\n";
else if(board[m]==EMPTY)
cout << "ITS EMPTY WTF WTF WTF\n";
for(int i=0;i<8;++i) //checking directions
{
Piece opp =(p==LIGHT)? DARK : LIGHT; //Making an opposite piece
cout << "made opp\n";
int counter=0;
int toCheck = m+offset[i]; //making the next square to check
if(board[toCheck]==opp) //if it's the opposite colour from player
{
cout << "it was the opposite piece\n";
while(board[toCheck]!=BORDER && board[toCheck]!=EMPTY) //while it's a piece
{
cout << "there was a piece to check\n";
if(board[toCheck]==p && counter>0) //if it's player's piece and counter is higher than 0
{
cout << "this should flip stuff\n";
for(int k=m;k!=toCheck;k = k+offset[i])
{
board[k]=p;
cout << k;
}
break;
}
else
{
cout << "found nothing, keep trying..\n";
toCheck += offset[i]; //if not, step in direction
counter++;
}
}
}
}
}
cout << "move wasn't in list\n";
}
}
currentPlayer=(p==LIGHT)? DARK : LIGHT;
}
bool Board::isLegal(Piece p, Move m)
{
Piece opp =(p==LIGHT)? DARK : LIGHT; //Making an opposite piece
if(board[m]==EMPTY) //Checking that the space we're going is empty
{
for(int i=0;i<8;++i) //checking directions
{
int toCheck = m+offset[i]; //making the next square to check
if(board[toCheck]==opp) //if it's the opposite colour from player
{
while(board[toCheck]!=BORDER && board[toCheck]!=EMPTY) //while it's a piece
{
if(board[toCheck]==p) //if it's player's piece
return true; // if move is valid
else
toCheck += offset[i]; //if not, step in direction
}
}
}
return false; // if there's no valid direction moves
}
else // if it's not empty
return false;
}
Piece Board::getWinner()
{
bool gameDone = true;
for(int i=0;i<MAX_SQUARES;++i)
{
if(board[i]==EMPTY)
gameDone = false;
}
if(gameDone==false)
return EMPTY;
else if(lightPieces>darkPieces)
return LIGHT;
else
return DARK;
}
Piece Board::getPlayer()
{
return currentPlayer;
}
void Board::genMoves()
{
goodMoves.clear();
cout << "generating shit\n";
for(int i=0;i<MAX_SQUARES;++i)
{
if(isLegal(currentPlayer, i))
{goodMoves.push_back(i);
cout << i << " twas a good move\n";}
}
if(goodMoves.size()==0)
gameOver=true;
}
int Board::numMoves()
{
return goodMoves.size();
}
Move Board::getMove(int i) const
{
return goodMoves[i];
}
Piece Board::currentPlayer=DARK;
Player.h
#include <iostream>
#include <cstdlib>
#ifndef PLAYER_H
#define PLAYER_H
#include "Board.h"
using namespace std;
class Player
{
public:
Player(const string&, Piece);
Piece getPiece() const;
virtual void makeMove(Board&)=0;
void setName(string&);
string getName();
private:
string name;
Piece color;
};
#endif
Player.cpp
#include <iostream>
#include <cstdlib>
#include "Player.h"
using namespace std;
Player::Player(const string& n, Piece c)
{
name = n;
color = c;
}
Piece Player::getPiece() const
{
return color;
}
void Player::setName(string& n)
{
name = n;
}
string Player::getName()
{
return name;
}
HumanPlayer.h
#include <iostream>
#include <cstdlib>
#include "Player.h"
#ifndef HUMANPLAYER_H
#define HUMANPLAYER_H
using namespace std;
class HumanPlayer: public Player
{
public:
HumanPlayer(const string&, Piece);
void makeMove(Board&);
};
#endif
HumanPlayer.cpp
#include <iostream>
#include <cstdlib>
#include "Player.h"
#include "HumanPlayer.h"
using namespace std;
HumanPlayer::HumanPlayer(const string& n, Piece c): Player(n,c)
{
}
void HumanPlayer::makeMove(Board& b)
{
Move goTo;
cout << "Please enter the number for the square you would like to move: ";
cin >> goTo;
if(!b.gameOver)
b.makeMove(getPiece(),goTo);
}
ComputerPlayer.h
#include <iostream>
#include <cstdlib>
#include "Player.h"
#ifndef COMPUTERPLAYER_H
#define COMPUTERPLAYER_H
using namespace std;
class ComputerPlayer: public Player
{
public:
ComputerPlayer(Piece p);
private:
static int counter;
//string name;
};
#endif
ComputerPlayer.cpp
#include <iostream>
#include <cstdlib>
#include "ComputerPlayer.h"
using namespace std;
ComputerPlayer::ComputerPlayer(Piece p) : Player("", p)
{
string name = "ComputerPlayer" + char(65+counter);
setName(name);
}
int ComputerPlayer::counter=0;
RandomPlayer.h
#include <iostream>
#include <cstdlib>
#include "ComputerPlayer.h"
#ifndef RANDOMPLAYER_H
#define RANDOMPLAYER_H
using namespace std;
class RandomPlayer : public ComputerPlayer
{
public:
RandomPlayer(Piece);
void makeMove(Board&);
};
#endif
RandomPlayer.cpp
#include <iostream>
#include <cstdlib>
#include "RandomPlayer.h"
using namespace std;
RandomPlayer::RandomPlayer(Piece p) : ComputerPlayer(p)
{
}
void RandomPlayer::makeMove(Board& b)
{
cout << "Player 2 making move in stuff\n";
b.genMoves();
int temp1 = b.numMoves();
cout << "This is temp1: " <<temp1 << '\n';
int temp2;
if(temp1>0)
{
temp2 = rand()%temp1;
}
//cout << "This is temp2: " <<temp2 << '\n';
if(!b.gameOver)
b.makeMove(getPiece(),b.getMove(temp2));
}
Game.h
// Name: James St-Germain
// Student #: 0270250
#include <iostream>
#include <cstdlib>
#include "Board.h";
#include "HumanPlayer.h"
#include "RandomPlayer.h"
#ifndef GAME_H
#define GAME_H
using namespace std;
class Game
{
public:
Game();
~Game();
void selectPlayers();
Player* nextPlayer();
void play();
void announceWinner();
private:
Board b;
Player *p1;
Player *p2;
bool isRunning;
};
#endif
Game.cpp
// Name: James St-Germain
// Student #: 0270250
#include "Game.h"
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
Game::Game(): b(), p1(NULL), p2(NULL), isRunning(true){}
Game::~Game()
{
delete &b;
delete &p1;
delete &p2;
}
void Game::selectPlayers()
{
string choice[2];
cout << "Is player 1 a human player or computer player? (H/C): \n";
cin >> choice[0];
cout << "Is player 2 a human player or computer player? (H/C): \n";
cin >> choice[1];
for(int i=0;i<2;++i)
{
if(choice[i]=="H")
{
string n;
char* c;
cout << "What is your name?: \n";
cin >> n;
if(i==0)
p1 = new HumanPlayer(n, LIGHT);
else
p2 = new HumanPlayer(n, DARK);
}
if(choice[i]=="C")
{
if(i==0)
p1 = new RandomPlayer(LIGHT);
else
p2 = new RandomPlayer(DARK);
}
}
cout << "Player 1 is " << p1->getName() << '\n';
cout << "Player 2 is " << p2->getName() << '\n';
}
Player* Game::nextPlayer()
{
if(b.getPlayer()==LIGHT)
return p2;
else
return p1;
}
void Game::play()
{
while(isRunning)
{
b.display();
Piece temp = b.getPlayer();
if(temp==LIGHT)
{
cout << "Player 1 moves!\n";
p1->makeMove(b);
}
else
{
cout << "Player 2 moves!\n";
p2->makeMove(b);
}
if(b.gameOver==true)
break;
}
}
void Game::announceWinner()
{
Piece winner = b.getWinner();
string name = (winner==LIGHT) ? p1->getName() : p2->getName();
cout << "The winner is " << name << "! Congratulations!\n";
}
main.cpp
#include <iostream>
#include <cstdlib>
#include "Game.h"
using namespace std;
int main()
{
Game Reversi = Game();
Reversi.selectPlayers();
Reversi.play();
Reversi.announceWinner();
}
I apologize for the extreme amount of code, but at this point, I don't know what to fix. I know there might also be bad coding habits here, so if you see any, I would love the constructive criticism.
Thank you in advance for all your help!!
This is probably because you have these declarations in the Game class:
Board b;
Player *p1;
Player *p2;
and this code in the destructor:
delete &b;
delete &p1;
delete &p2;
First of all, the Board member b is not a pointer so should not be deleted. Second of all, you're using the address-of operator to get the address of the pointer (and it will be a value of type Player**), which you don't allocate. Drop the &.