How do I pass an object, defined in Main, into a function?
My main function looks like this:
// Initialising the players
Player Joe;
Player Sid;
Joe.setPlayerName("Joe");
Sid.setPlayerName("Sid");
Joe.setPercentage(71);
Sid.setPercentage(73);
Joe.setTotal(501);
Sid.setTotal(501);
Joe.setThrows(0);
Sid.setThrows(0);
// Starts Joe's turn (and the game)
turn(Joe);
Within another function called calculateTotal, I have the following section of code:
else if (potentialTotal < 2 && potentialTotal != 0)
{
potentialTotal = total; // Total remains the same
player.setThrows(0); // Resets their throws
// Switch player's turn
if (player.getPlayerName() == "Joe")
{
turn(Sid);
}
else if (player.getPlayerName() == "Sid")
{
turn(Joe);
}
}
The problem is the Sid in turn(Sid) as well as Joe in turn(Joe) do not work, this is because they are declared in the main and not the calculateTotal function.
I have passed the Player object through as seen in calculateTotal function - player.getPlayerName() for example, but if I put turn(player), this would call turn(Joe) as he goes first which is not what I need, I need it to switch to Sid.
The functions in the program.
void turn(Player& player);
void bullseye(Player& player);
void singleThrow(int requiredValue, Player& player);
void doubleThrow(int dartThrow, Player& player);
void trebleThrow(int dartThrow, Player& player);
void calculateTotal(Player& player);
This is the error:
1>f:\abertay\programming\coursework\coursework\source.cpp(149): error C2065: 'Sid' : undeclared identifier
1>f:\abertay\programming\coursework\coursework\source.cpp(153): error C2065: 'Joe' : undeclared identifier
1>f:\abertay\programming\coursework\coursework\source.cpp(169): error C2065: 'Sid' : undeclared identifier
1>f:\abertay\programming\coursework\coursework\source.cpp(173): error C2065: 'Joe' : undeclared identifier
Pass a Reference
If you create your objects in the main and don't want copies of the objects (which appear to be the case), pass a reference to the objects in your main to your calculations function:
void calculations(Player& Joe, Player& Sid)
{
//...
else if (potentialTotal < 2 && potentialTotal != 0)
{
potentialTotal = total; // Total remains the same
player.setThrows(0); // Resets their throws
// Switch player's turn
if (player.getPlayerName() == "Joe")
{
turn(Sid);
}
else if (player.getPlayerName() == "Sid")
{
turn(Joe);
}
}
//...
}
If you are not familiar, a reference is simply another name for an object, it will not copy your Player objects, instead, calculations function will refer to the objects in the main function.
Related
void exp::example(std::string &a, std::string &b)
{
if (m_root.isObject() && m_root.isMember(a))
{
if (m_root[a].isMember(b))
{
m_root[a].append(b);
}
}
else
{
m_root[a] = Json::arrayValue;
m_root[a].append(b);
}
}
(m_root is defind in the hpp)
When I'm running this code I get the logic error:
in Json::Value::find(key, end, found): requires objectValue or nullValue.
I found out that I got this error from this if:
if (m_root[a].isMember(b))
I don't understand why do I get this error there, I used the same function in the if above him and I didn't get this error.
P.S the function is working until it enter the nested if, example:
a
b
m_root
"hey"
"a1"
{"hey":["a1"]}
"bye"
"a2"
{"hey":["a1"], "bye":["b1"]}
"cye"
"a3"
{"hey":["a1"], "bye":["b1"], "cye":["a3"]}
"hey"
"a4"
error: in Json::Value::find(key, end, found): requires objectValue or nullValue
I get the error only in the 4th call.
I appreciate your help!
On the 4th iteration you access the m_root["hey"] object which is of type arrayValue. Those values are not supported by the isMember method.
You'll have to find the value in the array in another way. I suggest iterating over the array, in something like:
bool is_inside_array(const Json::Value &json_array, const string& value_to_find)
{
for (const Json::Value& array_value: json_array) {
if (array_value.asString() == value_to_find) {
return true;
}
}
return false;
}
Then replace the inner if with:
if (is_inside_array(m_root[a], b))
I have a problem with my project, like I wrote in subject. I want to get a capacity from table of KeyPoint vector. Please tell me, where is my problem?
Here is my code
class SidesOfFigure
{
public:
SidesOfFigure() {
};
~SidesOfFigure() {
};
//sideNumber == 0 => top
//sideNumber == 1 => down
//sideNumber == 2 => left
//sideNumber == 3 => right
void setSideOfFigure(vector <KeyPoint> keyPoints, int sideNumber) {
sideOfFigure[sideNumber] = keyPoints;
}
uint64 getCapacityOfSide(int numberOfSide) {
try
{
return sideOfFigure[numberOfSide].capacity;
}
catch (const std::exception&)
{
throw exception("Illegal number!");
}
}
private:
vector <KeyPoint> sideOfFigure[4];
};
While the error message itself is relatively strange, the problem is that capacity is a member function of std::vector, not a member variable. So you just need to add parentheses to call it: sideOfFigure[numberOfSide].capacity().
I'm attempting to code a state machine based on a gumball machine. I have a interface class of a basic state, while I have specific states that use this interface. I have four states, no_quarter, has_quarter, sold, and sold_out states. I also have a gumball machine class that handles these states and depending on which state my machine is in, it will go that class and do the needed action. Here is my code that is having the problem, I'll post my functions also.
Gumball_Machine.h
class Gumball_Machine
{
private:
int gumball_count;
State *current_state;
No_Quarter_State *nqs;
Has_Quarter_State *hqs;
Sold_State *ss;
Sold_Out_State *sos;
public:
Gumball_Machine(int inventory)
{
gumball_count = inventory;
nqs = new No_Quarter_State(this);
hqs = new Has_Quarter_State(this);
ss = new Sold_State(this);
sos = new Sold_Out_State(this);
if (gumball_count == 0)
set_state(sos);
else
set_state(nqs);
}
void insert_quarter()
{
current_state->insert_quarter();
}
void eject_quarter()
{
current_state->eject_quarter();
}
void turn_crank()
{
current_state->turn_crank();
}
void dispense()
{
current_state->dispense();
}
void set_state(State *new_state)
{
current_state = new_state;
}
State *get_no_quarter_state()
{
return nqs;
}
State *get_has_quarter_state()
{
return hqs;
}
State *get_sold_state()
{
return ss;
}
State *get_sold_out_state()
{
return sos;
}
No_Quarter_State.h
#ifndef NO_QUARTER_STATE_H_INCLUDED
#define NO_QUARTER_STATE_H_INCLUDED
#include "State.h"
class No_Quarter_State: public State
{
public:
No_Quarter_State(Gumball_Machine *gbm);
void insert_quarter();
void eject_quarter();
void turn_crank();
void dispense();
};
#endif // NO_QUARTER_STATE_H_INCLUDED
No_Quarter_State.cpp
#include "No_Quarter_State.h"
#include "Gumball_Machine.h"
No_Quarter_State::No_Quarter_State(Gumball_Machine *machine)
{
machine = machine;
}
void No_Quarter_State::insert_quarter()
{
cout << "You inserted a quarter.\n";
machine->set_state(machine->get_has_quarter_state());
}
void No_Quarter_State::eject_quarter()
{
cout << "You must insert a quarter before you can eject one.\n";
}
void No_Quarter_State::turn_crank()
{
cout << "You must insert a quarter before you can crank the handle.\n";
}
void No_Quarter_State::dispense()
{
cout << "You need to pay first before you can get a gumball.\n";
}
The line I'm having an issue is in the No_Quarter_State.cpp
machine->set_state(machine->get_has_quarter_state());
This is giving me a run-time error. I've seen examples like this but I'm not completely sure if this is legal in C++. I'm attempting to switch the state of my gumball machine object.
The error I get is a generic not responding error: "test.ext has stopped working". I'm using CodeBlocks to code this.
In the constructor, the presumed member variable machine is hidden by the parameter.
No_Quarter_State::No_Quarter_State(Gumball_Machine *machine)
{
machine = machine;
}
You can fix this by using initializer list syntax instead:Thanks Sneftel and NathanOliver
No_Quarter_State::No_Quarter_State(Gumball_Machine *machine)
: machine(machine)
{
}
However, in regular method functions, you would have to use this-> if you named the method parameter the same as the member variable. A typical style used to avoid that issue is to prepend m_ or append _ to member names.
My method looks like this, getting an error during compilation "Read-only variable is not assignable" in vector.
What can be the problem?
int DownloadManager::RemoveDownload(const char *escapedTitle, const char *fileId)
{
boost::remove_if(Core::defaultCore().GetSocketsQueue()->GetQueue(), [&](SocketConnection* socket) {
if (strcmp(escapedTitle, socket->GetDownload()->escaped_title.c_str()) == 0 && strcmp(fileId, socket->GetDownload()->fileId.c_str()) == 0)
{
Core::defaultCore().GetDownloadQueue()->Remove(socket->GetDownload());
return true;
}
return false;
});
return 0;
}
Pasted just to show what GetQueue() above looks like.
std::vector<SocketConnection*> GetQueue()
{
return this->sockets_queue;
}
You should return reference from GetQueue, since now you are trying to remove from temporary variable, that is not allowed, because remove_if first parameter is expected to be reference, there is no conversion from temporary-variable to reference.
I would like to send back data to class that create this object.
It's game related.
The enemy objects have a threaded function and move on their own in the scene.
It generates lots of errors if you include the header file from the class that creates to the objects into the object itself ... to pass pointers.
Enemy Class:
Class Enemy
{
private:
void (*iChange)(DWORD &);
}:
Enemy::Enemy(void (*iChangeHandler)(DWORD &) ) : iChange(0)
{
this->iChange = iChangeHandler;
}
void Enemy::Draw(D3DGraphics& gfx)
{
this->iChange(this->dwThreadID); // send a message back to the class that created me
gfx.PutPixel(this->my_position_x + 0,this->my_position_y,this->red,this->blue,this->green);
this->grafix->DrawCircle(this->my_position_x + 0,this->my_position_y, this->radius, this->red,this->blue,this->green);
(sprintf)( this->enemy_buffer, "X: %d, Y: %d", this->my_position_x , this->my_position_y);
this->grafix->DrawString( this->enemy_buffer, this->my_position_x , this->my_position_y, &fixedSys, D3DCOLOR_XRGB(255, 0, 0) );
}
Game Class:
struct enemies_array_ARRAY {
std::string name;
DWORD ID;
Enemy* enemy;
} enemies_array[25];
void Game::EnemyEvent(DWORD &thread_id)
{
enemies_array[0]...... // i want to acces this struct array
}
Game::Game(HWND hWnd)
{
enemies_array[0].name = "john Doe";
enemies_array[0].ID = NULL;
enemies_array[0].enemy = new Enemy(&Game::EnemyEvent);
// error: C2664:
// another attemp
enemies_array[0].name = "john Doe";
enemies_array[0].ID = NULL;
enemies_array[0].enemy = new Enemy(Game::EnemyEvent);
// error C3867:
}
If I understand correctly, you want to call a function on the Game object. This means you need to pass a pointer to the Game object in order to correctly call a non static member function pointer(iChange) on it.
Make the changes shown below and you should be able to do what you want
enemies_array[0].enemy = new Enemy(this,&Game::EnemyEvent);
typedef void (Game::*ChangeFunc)(DWORD &)
Class Enemy
{
private:
ChangeFunc iChange;
Game *pGame;
}:
Enemy(Game *pCreatorGame, ChangeFunc iChangeHandler )
{
iChange = iChangeHandler;
pGame = pCreatorGame;
}
void Enemy::Draw(D3DGraphics& gfx)
{
(pGame->*iChange)(this->dwThreadID);