So, I’m trying to compile my code, but the compiler keeps complaining that “‘mysnake’ undeclared (first use this function)”, but I declared it.
This is my Main.cpp, wehre it is declared.
#include "Class.h"
#include "Snake.h"
int main(int argc, char* args[]){
Prog run;
if((run.Init())==false){
return(1);
}
Snake mysnake;
if(run.LoadFiles()==false){
return(1);
}
run.MainLoop();
if(run.Draw()==false){
return(1);
}
run.CleanUp();
return(0);
}
And this is the file that makes the compiler complain (AFAIK it’s the first file with any reference to ‘mysnake’ that gets compiled)
#include "Class.h"
#include<sstream>
#include "Snake.h"
bool Prog::Draw(){
std::stringstream message;
SDL_Rect position;
SDL_BlitSurface(image, NULL, screen, NULL);
int s=mysnake.EndSnake();
message<<"Your snake was "<<s<<" blocks long.";
msg=TTF_RenderText_Solid(font, message.str().c_str(), font_color);
if(msg==NULL){
return(false);
}
position.x=(WWIDTH-msg->w)/2;
position.y=(WHEIGHT-msg->h)/2;
SDL_BlitSurface(msg, NULL, screen, &position);
SDL_Flip(screen);
return(true);
}
I have thought about it for over an hour and I still can’t understand why it does this. By the way I’m using Bloodshed Dev C++
I’d be very grateful for help.
Inside your
Drawfunction there is no variable declared calledmysnake. That function can’t see themysnakethat’s declared inmainbecause it is local tomain. You need to pass yourmysnakeobject to theDrawfunction so that it knows which snake you’re actually talking about.To do that, give
Drawan argument of typeconst Snake&, a “reference toconst Snake” (or take away theconstifEndSnakeis a non-constmember function):And when you call
Drawinmain, do this:Now your
Drawfunction has a variable calledsnakewhich was passed in frommain. Because the argument is a reference, theSnakeobject that it sees is exactly the same object as inmain. If the argument had been of typeSnakeinstead ofconst Snake&, then you would get a copy of themysnakefrommain.Some extra advice:
We usually write conditions like
(run.Init())==falseas just!run.init()– it reads much better. Returning is also usually written asreturn true;, rather thanreturn(true);, but that’s up to you.