Question

I am writing a C++ Tic Tac Toe game, and this is what I have so far:

#include <iostream>
using namespace std;

int main()
{
    board *b;
    b->draw();
    return 0;
}
class board
{
    void draw()
    {
        for(int i = 0; i < 3;++i){
            cout<<"[ ][ ][ ]"<<endl;
        }
    }

};

However, when I created the pointer to board, CodeBlocks gave me an error: 'board' was not declared in this scope. How do I fix this? I am a new C++ programmer.

Était-ce utile?

La solution

You have at least the following issues ongoing:

  • You do not initialize the heap object before trying to access it. In this simple scenario, I would suggest a stack object instead of heap.

  • You do not have the board type known before instantiating it on the heap. Just move the board class declaration before the main function or forward declare it. In this simple case, I would just go with the "proper ordering".

  • The draw method is private since that is the default "visibility" in a class. You will need to mark it public. Alternatively, you could switch to struct instead of class to have the board method available as the default "visibility" is public in a struct.

This should fix your code:

#include <iostream>
using namespace std;

class board
{
public:
    void draw()
    {
        for(int i = 0; i < 3;++i){
            cout<<"[ ][ ][ ]"<<endl;
        }
    }

};

int main()
{
    board b;
    b.draw();
    return 0;
}

Autres conseils

You Should declare board class before main as at object creation time it don't know board class. and after that also code will crash because board* b will only make pointer which can point to board object, so need to change code as -

  #include <iostream>
  using namespace std;

class board
{  
 public :
 void draw()
  {
        for(int i = 0; i < 3;++i)
            cout<<"[ ][ ][ ]"<<endl;
  }
};
int main()
{
    board *b = new board();
    b->draw();
    if(b)
      delete b;
    b=0;
    return 0;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top