Unresolved external issue when compiling multi-source files - c++

I have a project that consists of 2 CPP files (main.cpp and Car.cpp) and a header file (Car.h). The program is meant to allow a user to enter the model, make, and speed of a car and displays the modified speed. My issue is that when I compile the project, I receive a "1 unresolved externals" issue like so:
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Car::Car(void)" (??0Car##QAE#XZ) referenced in function _main
1>C:\Users\Shaidi\Desktop\Classes\CIST 2362\Projects\main\Debug\main.exe : fatal error LNK1120: 1 unresolved externals
Here is the main.cpp file:
// main.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Car.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
string make;
int model, speed;
Car c;
//user input and assignment for make, model, and speed
cout << "Enter the make of the car: " <<endl;
cin >> make;
c.setMake(make);
cout << "Enter the model of the car: " <<endl;
cin >> model;
c.setYearModel(model);
cout << "Enter the speed of the car: " <<endl;
cin >> speed;
c.setSpeed(speed);
//print make and model
cout << "Car make: " << c.getMake() <<endl;
cout << "Car model: " << c.getYearModel() << endl;
cout << "Car speed: " << c.getSpeed() <<endl;
//loops to calculate and print acceleration and braking
for (int i = 0; i < 5; i ++){
cout << "Car speed after acceleration: " <<c.accelerate() <<endl;
}
for (int i = 0; i < 5; i ++){
cout << "Car speed after braking: " <<c.brake() <<endl;
}
return 0;
} //end main
Here is the Car.cpp file:
// Car.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Car.h"
#include <cstdlib>
#include <string>
#include <iostream>
using namespace std;
Car::Car(int y, string m)
{
string make = m;
int year = y;
speed = 0;
}
void Car::setYearModel(int y)
{
yearModel = y;
}
void Car::setSpeed(int s)
{
if (s >= 0){
speed = s;
} else {
cout << "Invalid speed";
exit(EXIT_FAILURE);
}
}
void Car::setMake(string m)
{
make = m;
}
int Car::getYearModel()
{
return yearModel;
}
int Car::getSpeed()
{
return speed;
}
string Car::getMake()
{
return make;
}
int Car::accelerate()
{
return speed + 5;
}
int Car::brake()
{
return speed - 5;
}
And here is the Car.h file:
#ifndef CAR_H
#define CAR_H
#include <string>
using namespace std;
class Car
{
private:
std::string make;
int yearModel;
int speed;
public:
Car();
Car(int, std::string);
void setYearModel(int);
void setSpeed(int);
void setMake(std::string);
int getYearModel() ;
int getSpeed() ;
int accelerate() ;
int brake() ;
std::string getMake() ;
};
#endif // CAR_H

You miss the implementation of default constructor of Car().
class Car
{
public:
// There is no implementation.
Car();
}

You've declared Car::Car() but never defined it. Either add a definition to the .cpp file, or remove the declaration from the header.
For example:
Car::Car()
{
}

It looks like you have defined the default constructor for car but have not implemented it. Then you declared a variable of type car which would require it to be implemented. Adding the code that Kerrek has above to the .cpp file should do the trick :)

Related

Multiple Definitions in C++ (Visual Basic 2010)

I'm attempting to practice some coding in my free time (combining a number of different interests of mine to help keep myself engaged) and I've encountered a odd error that I can't find the answer to. I have 4 files that I'm working with, two header files, one class definition file and a main file. I'm fairly confident I'm not including the Dice.h file more then once (however that is where the error points to and I'm not sure anymore, hence this question). What have I bungled here to produce these errors?
The error codes
Error 3 error LNK1169: one or more multiply defined symbols found (file path trimmed)
Error 2 error LNK2005: "int __cdecl dice(int,int)" (?dice##YAHHH#Z) already defined in Creature.obj (file path trimmed)
The filepath: c:\Users\Username\documents\visual studio2010\Projects\RPGTest\RPGTest\RPGTest.(error 3 referenced a .exe file, error 2 referenced a .obj file).
The code itself:
Dice.h
#ifndef SET_DICE_H_
#define SET_DICE_H_
#include <iomanip>
#include <iostream>
#include <stdlib.h>
using namespace std;
int dice(int number, int sides){
int total=0, dice;
srand(time(NULL));
int results=0;
do {
dice = rand()%sides+1;
total+=dice;
number--;
} while (number > 0);
results = total;
return results;
}
#endif
Creature.h
#ifndef CREATURE_H_
#define CREATURE_H_
#include <iomanip>
#include <iostream>
#include "Dice.h"
using namespace std;
class Creature {
public:
Creature(int,int,int,int,int,int,int,int,int,int,int,int);
void set_hp();
void set_saves();
void set_ac();
void set_bab();
void set_name();
void update_hp(int);
void update_ac(int);
void update_fsave(int);
void update_rsave(int);
void update_wsave(int);
int get_ac();
int get_hp();
int get_fsave();
int get_rsave();
int get_wsave();
int get_bonus(int);
int get_bab();
string get_name();
private:
int strength, dexterity, constitution, intellegence, wisdom, charisma;
int bab, fbsave, rbsave, wbsave;
int hdnum, hdsize;
int hp, fsave, rsave, wsave, ac;
string name;
};
#endif
Creature.cpp
#include "Creature.h"
#include <math.h>
#include <iostream>
using namespace std;
Creature::Creature(int strength,int dexterity,int constitution,
int intellegence,int wisdom,int charisma,int bab,int fbsave,
int rbsave,int wbsave,int hdnum,int hdsize){
strength = strength;
dexterity = dexterity;
constitution = constitution;
intellegence = intellegence;
wisdom = wisdom;
charisma = charisma;
bab = bab;
fbsave = fbsave;
rbsave = rbsave;
wbsave = wbsave;
hdnum = hdnum;
hdsize = hdsize;
}
int Creature::get_bonus(int stat){
int bonus = floor((double(stat)-10)/2);
return bonus;
}
void Creature::set_ac(){
ac=10+get_bonus(dexterity);
}
void Creature::set_hp(){
hp = dice(hdnum,hdsize) + get_bonus(constitution)*hdnum;
}
void Creature::set_saves(){
fsave = fbsave + get_bonus(constitution);
rsave = rbsave + get_bonus(dexterity);
wsave = wbsave + get_bonus(wisdom);
}
void Creature::set_bab(){
bab = hdnum;
}
void Creature::set_name(){
cout << "Please enter a name for this creature: ";
cout << "\nSorry! I don't work yet!";
cout << "\nInstead all creatures are named Larry!\n";
name = "Larry!";
}
void Creature::update_hp(int input){
hp = hp + input;
}
void Creature::update_fsave(int input){
fsave = fsave+input;
}
void Creature::update_rsave(int input){
rsave = rsave+input;
}
void Creature::update_wsave(int input){
wsave = wsave+input;
}
void Creature::update_ac(int input){
ac = ac+input;
}
int Creature::get_ac(){
return ac;
}
int Creature::get_hp(){
return hp;
}
int Creature::get_fsave(){
return fsave;
}
int Creature::get_rsave(){
return rsave;
}
int Creature::get_wsave(){
return wsave;
}
int Creature::get_bab(){
return bab;
}
RPGTest.cpp
#include "Creature.h"
#include <math.h>
//#include "Dice.h"
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int str = dice(3,6), dex = dice(3,6), con = dice(3,6), intel = dice(3,6), wis = dice(3,6), cha = dice(3,6);
int fbs = dice(1,6), rbs = dice(1,6), wbs = dice(1,6);
int hdn = dice(1,10), hds = 8, bab = dice(1,8);
cout << "Welcome to RPG Creature Tester v0.1\n";
cout << "This .exe file is meant to test the creature class functions and definitions.\n";
cout << "This will be done by randomly generating and displaying a creature.\n";
cout << "What you don't see right now is the random generation of a creature.\n";
cout << "Once it's finished, the \'statsheet\' will be shown.\n";
cout << "Cheers!\n\n";
Creature potato (str, dex, con, intel, wis, cha, bab, fbs, rbs, wbs, hdn, hds);
potato.set_ac();
potato.set_hp();
potato.set_name();
potato.set_saves();
cout << "OUTPUT BRICK YAY\n";
cout << "Str: " << str << endl;
cout << "HP: " << potato.get_hp() << " AC: " << potato.get_ac() << " Fort/Reflex/Will Save: " << potato.get_fsave() << "/" << potato.get_rsave() << "/" << potato.get_wsave();
return 0;
}
Since I'm mainly self-taught I'm happy for any other advice but my main issue is that I'm not sure why I'm getting the "multiple" definition error. I did some research into other questions with similar error messages but I didn't see anything that immediately jumped out at me as "the answer".
Thanks all!
C++ works by compiling single translation units and then linking them together.
This means that each source file gets compiled on its own. Since the #include directive basically inserts all the code included, in your situation you end up having multiple translation units which define
int dice(int number, int sides) {
...
}
Compilation goes through fine but, when linking, multiple definition of this function are found so this generates the error.
To solve this problem you have two ways:
declare int dice(int, int) in a header file but define (implement it) in a source file
keep the definition as it is but prepend static to it. This tells the compiler that each translation unit will get its own dice method. This solution, although tempting, leads to binary size increase since you will have multiple implementation of the same method

C++ Decorator - Not working properly

First Issue Resolved
As voiced in the answers below , i incorrectly wrote the
#ifndef ICETOWER_H
#define ICETOWER_H
I'm still having some problem with my c++ code.
I implemented a decorator pattern to upgrade a basic tower to an ice tower with 2* the cost. but when i run it , its displaying the same specs for both towers even after it has been decorated . Anyone have any idea what i did wrong ?
Here are the files :
tower.h
#ifndef __TOWER_H__
#define __TOWER_H__
#include <iostream>
#include <string>
using namespace std;
class Tower {
private:
string type;
string effect;
int cost;
int sellTower;
int damage;
int range;
int rate;
public:
string getType() { return type; }
string getEffect() { return effect; }
int getCost() { return cost; }
int getSale() { return sellTower; }
int getDamage() { return damage; }
int getRange() { return range; }
int getROF() { return rate; }
Tower();
virtual ~Tower(){}
};
#endif __TOWER_H__
tower.cpp
#include "Tower.h"
Tower::Tower()
{
// Tower Type
this->type = "Basic";
// Tower Special Effect
this->effect = "None";
// Tower Cost
this->cost = 500;
// Tower Sell Cost
this->sellTower = 300;
// Tower Damage inflicted
this->damage = 50;
// Tower Range (paths)
this->range = 2;
// Tower rate of fire
this->rate = 0.5;
};
TowerDecorator.h
#ifndef __TOWERDECORATOR_H__
#define __TOWERDECORATOR_H__
#include <iostream>
#include <string>
#include "Tower.h"
using namespace std;
class TowerDecorator : public Tower {
private:
Tower *decoratedTower;
public:
TowerDecorator(Tower *decoratedTower)
{
this->decoratedTower = decoratedTower;
}
string type() { return decoratedTower->getType(); }
string effect() { return decoratedTower->getEffect(); }
int getCost() { return decoratedTower->getCost(); }
int getSale() { return decoratedTower->getSale(); }
int getDamage() { return decoratedTower->getDamage(); }
int getRange() { return decoratedTower->getRange(); }
int getROF() { return decoratedTower->getROF(); }
};
#endif __TOWERDECORATOR_H__
iceTower.h
#ifndef ICETOWER_H
#define ICETOWER_H
#include "TowerDecorator.h"
class IceTower : public TowerDecorator {
public:
IceTower(Tower *decoratedTower) : TowerDecorator (decoratedTower){}
int getCost(){return TowerDecorator::getCost() * 2;}
};
#endif __ICETOWER_H__
Driver.cpp
#include "Tower.h"
#include "TowerDecorator.h"
#include "IceTower.h"
void printTowerDetails(Tower* tower)
{
cout << endl << "This is a " << tower->getType() << " Tower" << endl;
cout << "Build Tower : " << tower->getCost() << " Coins" << endl;
cout << "Sell Tower : " << tower->getSale() << " Coins" << endl;
cout << "Tower Range : " << tower->getRange() << " paths" << endl;
cout << "Tower Rate Of Fire : " << tower->getROF() << " p/s" << endl;
cout << "Tower Special Effect : " << tower->getEffect() << "" << endl;
}
int main() {
Tower *t1 = new Tower();
printTowerDetails(t1);
t1 = new IceTower(t1);
printTowerDetails(t1);
}
Output :
Image : http://i.imgur.com/Ws018iV.png
There are at least two serious errors.
The first one is that you check definitions of manifest constants with suffix _H__ but define them without the suffix:
#ifndef __TOWER_H__
#define __TOWER__
and
#ifndef __TOWERDECORATOR_H__
#define __TOWERDECORATOR__
The second one is that you forgot to place a semicolon after class definition of TowerDecorator
class TowerDecorator : public Tower {
//...
}
Well, the first problem that you have is a problem with your include guard. It should be:
#ifndef __TOWER_H__
#define __TOWER_H__
You might have other problems as well.
BTW, you shouldn't use names that begin with two underscores, since they are reserved.
Your header gaurds are inconsistent:-
#ifndef __TOWER_H__
#define __TOWER__
This should be
#ifndef __TOWER_H__
#define __TOWER_H__
Secondly change this
#endif __TOWER_H__
to
#endif

Error LNK2005 object already defined

I have two .cpp files:
class.cpp
#include "stdafx.h"
#include "vehicles.h"
#include <iostream>
#include <time.h>
using MAP_GRID = vector<vector<string>>;
using namespace std;
void print_terrain(MAP_GRID);
void set_position(MAP_GRID &, int, int, vehicles::position, string);
void random_position(MAP_GRID &, int, string);
MAP_GRID create_terrain();
MAP_GRID MAP = create_terrain();
int _tmain(int argc, _TCHAR* argv[])
{
tanks t34(12, 0.5, 21,6);
srand(time(NULL));
//set_position(MAP, 5, 5, t34.pos,"[x]");
random_position(MAP, 12, "[o]");
print_terrain(MAP);
//[...]
}
and terrain.cpp
#include "stdafx.h"
#include <iostream>
#include <vector>
#include "vehicles.h"
#define MIN_SIZE 6
#define MAX_SIZE 15
using std::vector;
using std::string;
using MAP_GRID = vector<vector<string>>;
int global_size;
void set_position(MAP_GRID &MAP, int x, int y, vehicles::position &pos, string object)
{
if (x <= MAP.size() || y <= MAP.size())
if (MAP[x][y] != "[ ]")
std::cout << "\nPosition is occupied" << std::endl;
else
{
MAP[x][y] = object;
pos.x.push_back(x);
pos.y.push_back(y);
}
else
std::cout << "\Choose correct position" << std::endl;
}
//[...]
and also header file:
#include <iostream>
#include <vector>
using namespace std;
using std::vector;
using MAP_GRID = vector<vector<string>>;
void change_position(MAP_GRID &, int, int);
class vehicles{
protected:
double durability;
double velocity;
public:
vehicles(double d, double v) : durability(d), velocity(v) {}
~vehicles() {}
void drive();
void info() { cout << durability << " " << velocity << "\n"; }
struct position{
vector<int> x;
vector<int> y;
}pos;
};
class tanks:public vehicles{
private:
double damage;
public:
tanks(double dmg, double v, double d, int m) :vehicles(d, v), damage(dmg), ammo(m) {}
~tanks() {}
int ammo;
void shoot();
void info();
};
void tanks::shoot(){
if (ammo >= 0)
{
cout << "You deal " << damage << ". You have " << ammo << "ammo left.\n\n";
ammo-=1;
}
else
cout << "You don't have ammo\n\n";
}
void tanks::info(){
cout << "You velocity " << velocity << endl;
cout << "You durability " << durability << endl;
cout << "You damage " << damage << endl;
}
The compiler (Microsoft Visual Studio 2013) gives me these errors:
terrain.obj : error LNK2005: "public: void __thiscall tanks::info(void)" (?info#tanks##QAEXXZ) already defined in class.obj
terrain.obj : error LNK2005: "public: void __thiscall tanks::shoot(void)" (?shoot#tanks##QAEXXZ) already defined in class.obj
class.exe : fatal error LNK1169: one or more multiply defined symbols found
I know it's a common question about this error, but I'm trying remove it, without success.
Move tanks::shoot() and tanks::info() to terrain.cpp or class.cpp file. Or create vehicles.cpp and move definitions there.
You are including vehicles.h from two source files, so both object files (class.obj and terrain.obj) have tanks::shoot() and tanks::info() defined, but there should be only one definition, hence the error.

Debug Assertion Failed! Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

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 &.

Unresolved Externals, Unresolved external symbol LNK 1120

I am making a bank account program and can not figure out why I keep getting the following error:
Error 5 error LNK1120: 1 unresolved externals
I have a superclass BankAccount and a child class Checking Account.
Bank Account .h:
#pragma once
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class BankAccount
{
public:
BankAccount::BankAccount();
BankAccount::~BankAccount();
virtual void depsoit(double money) = 0;
virtual double withdraw(double money) = 0;
virtual double getBalance() = 0;
virtual void endOfMonth() = 0;
private:
double balance;
};
Bank account .cpp
#include "BankAccount.h"
#include <iostream>
#include <vector>
using namespace std;
BankAccount::BankAccount()
{
balance = 0;
}
BankAccount::~BankAccount()
{
}
CheckingAccount.h
#pragma once
#include "BankAccount.h"
#include <vector>
#include <iostream>
using namespace std;
class CheckingAccount :
public BankAccount
{
public:
CheckingAccount();
~CheckingAccount();
void depsoit(double money);
double withdraw(double request);
double getBalance();
void endOfMonth();
private:
double checkingBalance=0;
int transactionLimit = 5;
float fee = .05;
double fees=0;
vector <double> feeTransactions;
};
CheckingAccount.cpp
#include "CheckingAccount.h"
#include <iostream>
#include <vector>
using namespace std;
CheckingAccount::CheckingAccount()
{
checkingBalance = 0;
}
CheckingAccount::~CheckingAccount()
{
}
void CheckingAccount::depsoit(double money)
{
if (transactionLimit > 0)
{
transactionLimit--;
cout << "You have " << transactionLimit << " transactions left";
checkingBalance += money;
}
else
{
feeTransactions.push_back(money);
cout << "Your transaction went through but you incurred a fee";
checkingBalance += money;
}
}
double CheckingAccount::withdraw(double request)
{
if (checkingBalance < request)
{
cout << "Sorry you do not have the available funds";
return 0.0;
}
else if (transactionLimit > 0)
{
transactionLimit--;
cout << "You have " << transactionLimit << " transactions left";
checkingBalance -= request;
return request;
}
else
{
feeTransactions.push_back(request);
cout << "Your transaction went through but you incurred a fee";
checkingBalance -= request;
return request;
}
}
double CheckingAccount::getBalance()
{
return checkingBalance;
}
void CheckingAccount::endOfMonth()
{
for (int i = 0; i < feeTransactions.size(); i++)
{
fees = feeTransactions[i] * fee;
}
checkingBalance -= fees;
}
And finally MAIN.CPP
#include "CheckingAccount.h"
#include <iostream>
#include <vector>
using namespace std;
int main()
{
CheckingAccount test();
test().getBalance();
//system("PAUSE");
return 1;
}
The error message again is:
Error 4 error LNK2019: unresolved external symbol "class
CheckingAccount __cdecl test(void)" (?test##YA?AVCheckingAccount##XZ)
referenced in function _main C:...Main.obj Assignment1Part3A
You are not declaring a variable of type CheckingAccount here:
CheckingAccount test();
What you are doing is declaring a function test which returns an object of type CheckingAccount and takes in no parameters.
Do it as follows:
CheckingAccount test{};
You should call getBalance as follows:
test.getBalance(); and not test().getBalance();
Well the error tells you exactly what's the problem. It's in your main: test().getBalance();. You are calling test as it was a function, but it's an object name. It should be just test.getBalance(). The previous line should be without the () too, but they should be fine there, because the compiler is treating them as a constructor in that case.