Pregunta

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.

¿Fue útil?

Solución

Inside your Draw function there is no variable declared called mysnake. That function can't see the mysnake that's declared in main because it is local to main. You need to pass your mysnake object to the Draw function so that it knows which snake you're actually talking about.

To do that, give Draw an argument of type const Snake&, a "reference to const Snake" (or take away the const if EndSnake is a non-const member function):

bool Prog::Draw(const Snake& snake) {
  // ...
}

And when you call Draw in main, do this:

run.draw(mysnake);

Now your Draw function has a variable called snake which was passed in from main. Because the argument is a reference, the Snake object that it sees is exactly the same object as in main. If the argument had been of type Snake instead of const Snake&, then you would get a copy of the mysnake from main.


Some extra advice:

We usually write conditions like (run.Init())==false as just !run.init() - it reads much better. Returning is also usually written as return true;, rather than return(true);, but that's up to you.

Otros consejos

The fact that mysnake is declared in main does not allow one to use it in Prog. You probably want to transmit a reference to mysnake to the Draw method. Through the constructor or through the call to the method.

Prog run(mysnake);
run.draw();

or

run.draw(mysnake);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top