I would like to understand aggregation so I tried making a simple test code, but it doesn't work in my compiler, sometimes it works online.
code for main:
#include <iostream>
#include <string>
#include "player.h"
#include "game.h"
using namespace std;
int main(){
game game;
game.playGame();
return 0;
}
code for game.cpp:
#include "game.h"
#include "player.h"
game::game(){
player.setBalance(0);
}
void game::playGame(){
cout << "playing game." ; //just for debugging
}
code for game.h:
#ifndef GAME
#define GAME
#include <iostream>
using namespace std;
class game{
private:
player player;
public:
game();
void playGame();
};
#endif
code for player.cpp:
#include "player.h"
player::player(){
balance = 0;
}
player::player(int theBalance){
balance = theBalance;
}
int player::getBalance(){
return balance;
}
void player::setBalance(int theBalance){
balance = theBalance;
}
code for player.h:
#ifndef PLAYER // used on headers
#define PLAYER
class player{
private:
int balance;
public:
player();
player(int);
int getBalance();
void setBalance(int);
};
#endif
I think the problem is probably on the headers.
the error I get is:
In file included from main.cpp:5:0:
game.h:10:12: error: declaration of 'player game::player' [-fpermissive]
player player;
In file included from main.cpp:4:0:
player.h:5:7: error: changes meaning of 'player' from 'class player' [-fpermissive]
class player{
^~~~~~
I think that the problem is in class game, because it doesn't know a class player, use forward declaration or just write #include "player.h" in game.h
Related
I have to do polymorphism for the go() function but i cant figure out how to access private variable distance. The complier keeps showing that
‘int Transport::distance’ is private within this context
5 | distance = 100;
Here is my code
Transport.h
#ifndef TRANSPORT_H
#define TRANSPORT_H
#include <iostream>
using namespace std;
class Transport{
private:
int distance;
public:
int get_dist_travelled();
virtual void go();
};
#endif
Transport.cpp
#include "Transport.h"
int Transport::get_dist_travelled(){
return distance;
}
Horse.h
#ifndef HORSE_H
#define HORSE_H
#include <iostream>
#include "Transport.h"
using namespace std;
class Horse:public Transport{
public:
void go();
};
#endif
Horse.cpp
#include "Horse.h"
#include "Transport.h"
void Horse::go() {
distance = 100;
}
main.cpp
#include <iostream>
#include "Transport.h"
#include "Horse.h"
using namespace std;
int main(){
Horse kid;
kid.go();
cout<<kid.get_dist_travelled()<<endl;
}
You can on the one hand make the variable protected, or define the class as a friend class.
I'm trying to add inheritance to my objects based on SFML and I can't solve a problem with errors
*expected class-name before '{' token*
and when I try to solve it by pre-declaring my parent class I'm getting stopped by
*invalid use of incomplete type 'class Object'*
I made Rectangle and Circle class with Object as parent class
Object.hpp
#ifndef OBJECT_HPP_INCLUDED
#define OBJECT_HPP_INCLUDED
#include "../MainClass.hpp"
#include "../Data/Data.hpp"
#include <SFML/Graphics.hpp>
#include <iostream>
class Object
{
public:
Object();
virtual ~Object();
virtual void update() = 0;
virtual void draw() = 0;
};
#endif // OBJECTPARENT_HPP_INCLUDED
in Object.cpp file I only have definitions of constructor and deconstructor
Rectangle.hpp
#ifndef RECTANGLE_HPP_INCLUDED
#define RECTANGLE_HPP_INCLUDED
#include "Object.hpp"
#include <SFML/Graphics.hpp>
#include "../Data/Data.hpp"
#include "../MainClass.hpp"
#include <iostream>
#include <cstdlib>
class Object; // <--- without this line *expected class-name before '{' token*, but with it *invalid use of incomplete type 'class Object'*
class Rectangle : public Object
{
public:
Rectangle(/*args*/);
virtual ~Rectangle();
//some functions
void update();
void draw();
private:
//some members
};
#endif // RECTANGLE_HPP_INCLUDED
and Circle.hpp
#ifndef CIRCLE_HPP_INCLUDED
#define CIRCLE_HPP_INCLUDED
#include "Object.hpp"
#include <SFML/Graphics.hpp>
#include "../Data/Data.hpp"
#include "../MainClass.hpp"
#include <iostream>
#include <cstdlib>
class Object; // <--- without this line *expected class-name before '{' token*, but with it *invalid use of incomplete type 'class Object'*
class Circle: public Object
{
public:
Circle(/*args*/);
virtual ~Circle();
//some functions
void update();
void draw();
private:
//some members
};
#endif // CIRCLE_HPP_INCLUDED
I don't know what to do, I tried changing the order of all includes, removing stuff and adding it, i searched everywhere but there was no good solution. Thank you for all answers
just insert ' #include "Object.hpp" ' in Circle.hpp and Rectangle.hpp and any other file like them that is using Object class:
#include "ObjectParent.hpp"
#include <SFML/Graphics.hpp>
#include "../Data/Data.hpp"
#include "../MainClass.hpp"
#include "Object.hpp" // <----------
#include <iostream>
#include <cstdlib>
I am trying to make a little poker game. In the code below I have a Game class and a Player class. The game class contains a std::vector which contains all the players. The Player class has a name attribute. Now my question is the following: how can I access the Player's attribute name through the vector that contains the Player objects? My problem appears in the last method of the code below, called show().
Thanks for helping!
//Player.h
#ifndef PLAYER_H
#define PLAYER_H
#include <iostream>
#include "Card.h"
class Player
{
public:
Player();
Player(std::string n, double chipsQty);
private:
const std::string name;
double chipsAmount;
Card cardOne;
Card cardTwo;
};
#endif PLAYER_H
//Player.cpp
#include "Player.h"
Player::Player(){}
Player::Player(std::string n, double chipsQty) : name(n), chipsAmount(chipsQty)
{}
//Game.h
#ifndef GAME_H
#define GAME_H
#include "Player.h"
#include <vector>
class Game
{
public:
Game();
Game(int nbr, double chipsQty, std::vector<std::string> vectorNames);
void start();
void show();
private:
std::vector<Player> playersVector;
int nbrPlayers;
};
#endif GAME_H
//Game.cpp
#include "Game.h"
#include "Player.h"
Game::Game(){}
Game::Game(int nbr, double chipsQty, std::vector<std::string> vectorNames) :nbrPlayers(nbr)
{
for (int i = 0; i < vectorNames.size(); i++)
{
Player player(vectorNames[i], chipsQty);
playersVector[i] = player;
}
}
void Game::start(){};
void Game::show()
{
for (int i = 0; i < playersVector.size(); i++)
{
std::cout << playersVector[i] //Why can't I do something like playersVector[i].name here?
}
}
Because name attrbute of a Player class is private, so you cannot access it directly from another class. You should add a method to Player class that will return the name of the player, eg:
class Player
{
private:
std::string name;
public:
std::string getName() const { return name; }
};
Then you can access the player name by
playersVector[i].getName()
OK so i have a few problems.
1. I need to be able to register the childclass when its created with game for broadcasting.
2. I need to be able to call the child class's method from an array of GameObject Pointers.
3. I need it to be the actual classes, not just copys of them.
In the file systemvars.h i have my global methods and some variables.
#pragma once
//=================================
// include guard
#ifndef _SYSTEMVARS_H_
#define _SYSTEMVARS_H_
//=================================
// forward declared dependencies
class Game;
//=================================
// included dependencies
#include <iostream>
using namespace std;
//global enums
const enum CLASSTYPE{CLASSTYPE_NULL,CLASSTYPE_PLAYER,CLASSTYPE_DUNGION,CLASSTYPE_ENTITY,CLASSTYPE_MAP,CLASSTYPE_MENU};
//Global methods
void setGameRefrence(Game*);
Game* getGameRefrence();
systemvars.cpp: definitions
#include "SystemVars.h"
static Game* curentgame;
void setGameRefrence(Game* mygame)
{
curentgame = mygame;
}
Game* getGameRefrence()
{
return curentgame;
}
In my Game.h: a holder for gameobjects
#pragma once
//=================================
// include guard
#ifndef _GAME_H_
#define _GAME_H_
//=================================
// forward declared dependencies
class GameObject;
//class Player;
//=================================
// included dependencies
#include "SystemVars.h"
#include "GameObject.h"
//#include "Player.h"
#include <iostream>
using namespace std;
//=================================
// the actual class
class Game
{
public:
Game(void);
void registerGameObject(GameObject*);
void unregisterGameObject(GameObject*);
void sendMessageToAllObjects(string message,CLASSTYPE recipeint);
~Game(void);
private:
GameObject *gameobjects2[1000];
int numberofobject;
};
#endif
the game.cpp gameclass definition
#include "Game.h"
//#include "Player.h"
Game::Game(void)
{
setGameRefrence(this);
//logHelperMessage(INFO,1,"Registerd game");
numberofobject = 0;
}
void Game::registerGameObject(GameObject* newobj)
{
//logHelperMessage(INFO,1,"Registerd");
newobj->setId(numberofobject);
gameobjects2[numberofobject] = newobj;
numberofobject++;
//gameobjects.push_back(newobj);
}
void Game::unregisterGameObject(GameObject* objtodie)
{
//logHelperMessage(INFO,1,"Unregister");
for(int i = objtodie->getId();i < numberofobject - 1;i++)
{
gameobjects2[i] = gameobjects2[i+1];
gameobjects2[i]->setId(i);
}
gameobjects2[numberofobject-1] = nullptr;
numberofobject--;
}
void Game::sendMessageToAllObjects(string message,CLASSTYPE recipeint)
{
for(int i = 0; i < numberofobject;i++)
{
cout << "Sent the message from game");
//((Player *)gameobjects2[i])->sendMessage(message);
//static_cast<Player*>(gameobjects2[i])->sendMessage(message);
}
}
Game::~Game(void)
{
}
Gameobject.h: the parent of my inner game classes.
#pragma once
//=================================
// include guard
#ifndef _GAMEOBJECT_H_
#define _GAMEOBJECT_H_
//=================================
// forward declared dependencies
enum CLASSTYPE;
//=================================
// included dependencies
#include <iostream>
#include "SystemVars.h"
using namespace std;
//=================================
// the actual class
class GameObject
{
public:
GameObject();
GameObject(CLASSTYPE mytype);
~GameObject(void);
virtual void sendMessage(string data);
virtual CLASSTYPE getMyClassType();
virtual void setMyClassType(CLASSTYPE newrecip);
void setId(int val);
int getId();
protected:
CLASSTYPE _MYCURRENTCLASSTYPE;
int myid;
};
#endif
Gameobject.cpp
#include "GameObject.h"
GameObject::GameObject() : _MYCURRENTCLASSTYPE(CLASSTYPE_NULL)
{
//do not register
}
GameObject::GameObject(CLASSTYPE mytype): _MYCURRENTCLASSTYPE(mytype)
{
//register this object into the gameobject list.
getGameRefrence()->registerGameObject(this);
}
GameObject::~GameObject(void)
{
getGameRefrence()->unregisterGameObject(this);
}
void GameObject::sendMessage(string data)
{
//logHelperMessage(INFO,1,"Recived te message in GameObject");
cout << "Recived te message in GameObject";
}
CLASSTYPE GameObject::getMyClassType()
{
return _MYCURRENTCLASSTYPE;
}
void GameObject::setMyClassType(CLASSTYPE newrecip)
{
}
void GameObject::setId(int val)
{
myid = val;
}
int GameObject::getId()
{
return myid;
}
Player.h:
pragma once
//=================================
// include guard
#ifndef _PLAYER_H_
#define _PLAYER_H_
//=================================
// forward declared dependencies
//=================================
// included dependencies
#include "SystemVars.h"
#include "GameObject.h"
//=================================
// the actual class
class Player : public GameObject
{
public:
Player();
void sendMessage(string data) override;
void test();
}
Player.cpp:
Player::Player() : GameObject(CLASSTYPE_PLAYER)
{
}
void Player::sendMessage(string data)
{
//logHelperMessage(INFO,1,"Recived the message in Player");
cout << "Recived the message in Player";
//logHelperMessage(INFO,1,data.c_str());
cout << data;
}
void Player::test()
{
cout << "Sent message";
getGameRefrence()->sendMessageToAllObjects("Test",CLASSTYPE_PLAYER);
}
main.cpp
#pragma once
#include "SystemVars.cpp"
#include "Player.h"
#include "Game.h"
Game mygame;
int main(int argc, char **argv)
{
setGameRefrence(&mygame);
Player newplayer = Player();
newplayer.test();
}
Now that that is all out of the way.
The expected output is:
Sent message
Sent message from game
Recived message in Player
but insted i get:
Sent message
Sent message from game
Recived message in Gameobject
Im pretty sure i have a sliceing problem, but im not sure what to do about it, or where it is.
So, any ideas gents?
ALso, i tried to cut back the classes a bit so im not posting 2000~ lines of code. So if anyhting missing let me know.
About a dozen classes inherit from gameobject. and i need them all to talk to eachother in one way or another.
Just by having CLASSTYPE_PLAYER, etc. makes me concerned that you're trying to subvert/reinvent C++ OOP. You already have the concept of 'class' in the language, why re-invent it? Forgive me if I'm wrong. Aside from this, I suggest you look up publisher-subscriber frameworks to do the kind of thing you're after, or implement your own. I'm sure somebody will answer your C++ issue more directly.
Edit: tone of first comment.
I have 3 classes namely Board, Game, and AI
i want to have the object chessBoard of Board class to be use by Game and AI, and also by the Board Class. I want them to access that single chessBoard object (sharing)
problem is, it gives me the infamous fatal error LNK1169: one or more multiply defined symbols found. Also, there are Board.h,Game.h and AI.h (only declarations in them), and i also have their corresponding .cpp files. Each .h files have guards included (#ifndef _XXXXXX_H_)
I tried to include Board chessBoard inside Board.h file (just below the class), and it seems guards are not working.
Error 7 error LNK2005: "class Board chessBoard" (?chessBoard##3VBoard##A) already defined in AI.obj C:\Users\xxxx\Documents\Visual Studio 2010\Projects\CHESSv3\CHESSv3\Board.obj CHESSv3
Error 8 error LNK2005: "class Board chessBoard" (?chessBoard##3VBoard##A) already defined in AI.obj C:\Users\xxxxx\Documents\Visual Studio 2010\Projects\CHESSv3\CHESSv3\Game.obj CHESSv3
Error 9 error LNK2005: "class Board chessBoard" (?chessBoard##3VBoard##A) already defined in AI.obj C:\Users\xxxxx\Documents\Visual Studio 2010\Projects\CHESSv3\CHESSv3\ProgramEntryPoint.obj CHESSv3
AI.h
#ifndef _AI_H_
#define _AI_H_
#include <iostream>
#include <string>
using namespace std;
struct node {
string position;
string nextPosition;
float score;
int level;
float totalscore;
node* up;
node* right;
node* left;
bool approved;
string move;
};
class AI {
private:
//string board;
//string board[8][8];
int score1;
int maxscore;
int totalscore;
public:
void GetBoard(string[][8]);
void AnalyzeMyPositions();
void ExecuteAdvanceHeuristicMove();
};
#endif
Game.h
#ifndef _GAME_H_
#define _GAME_H_
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <queue>
#include <stack>
#include <cmath>
using namespace std;
class Game {
public:
char WhosTurn();
bool Playable();
bool GetMoveFromPlayer();
void TurnOver();
Game();
private:
char turn;
};
#endif
Board.h
#ifndef _BOARD_H_
#define _BOARD_H_
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <queue>
#include <stack>
#include <cmath>
using namespace std;
class Board {
public:
bool SquareChecker(string);
bool MoveChecker(string);
Board();
void PrintBoard();
int Execute(string);
void UnExecute();
string CB[8][8];
private:
char turn;
vector<string> BoardRecord;
stack<string> CBR;
//string CB[8][8];
};
Board chessBoard;
#endif
If you really want to do this, you need to make the declaration of the object extern in the header Board.h:
extern Board chessBoard;
You then provide a declaration in Board.cpp:
Board chessBoard;
Much better, though would be to create it in enclosing code and pass it (by reference) to the constructors of the other classes.
What you are looking for is the Singleton design pattern which can achieved in the following way:
// Board.h
class Board {
private:
static instance_;
public:
static Board *instance();
}
// Board.cpp
Board *Board::instance_ = NULL;
Board *Board::instance() {
if (!instance_)
instance_ = new Board();
return instance_;
}
Mind that this pattern can either be seen as good or bad, if you don't like using it you should consider passing the reference of an instantiated Board class to all the requiring ones and keep it stored in each object as an instance variable. Something like:
Game::Game() {
this->board = new Board();
this->ai = new AI(board);
// or better this->ai = new AI(this) so AI can access all game methods
}
Your problem could be that there could be 3 different chessBoard definitions because you might be adding 3 different #include "Board.h". Please make only a single object at a place where you have more control rather than creating it globally inside Board.h
Did you try it like this? Include the necessary include declarations only in the .cpp files.
//Board.h
class Board {};
//Game.h
class Board;
class Game {
Board* myBoard;
public:
void setBoard(Board*);
};
//AI.h
class Board;
class AI {
Board* myBoard;
public:
void setBoard(Board*);
};
void main() {
Board chessBoard;
Game g;
g.setBoard(&chessBoard);
AI ai;
ai.setBoard(&chessBoard);
}