'板'在这方面没有申明

时间:2014-04-20 16:27:53

标签: c++ class codeblocks

我正在写一个C ++ Tic Tac Toe游戏,这是我到目前为止所做的:

#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;
        }
    }

};

然而,当我创建指向板的指针时,CodeBlocks给了我一个错误:&#39; board&#39;在这方面没有申明。我该如何解决?我是一名新的C ++程序员。

2 个答案:

答案 0 :(得分:4)

您至少还有以下问题:

  • 在尝试访问堆对象之前,不要初始化堆对象。在这个简单的场景中,我建议使用堆栈对象而不是堆。

  • 在堆上实例化之前,您没有已知的板类型。只需在main函数之前移动board类声明或者向前声明它。在这个简单的例子中,我会选择&#34;正确的订购&#34;。

  • 绘制方法是私有的,因为这是默认的&#34;可见性&#34;在课堂上。您需要将其标记为公开。或者,您可以切换到struct而不是class,以使board方法可用作默认&#34; visibility&#34;在结构中公开。

这应修复您的代码:

#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;
}

答案 1 :(得分:0)

你应该在main之前声明board class,因为在创建对象时它不知道board class。 之后代码也会崩溃,因为board * b只会生成指向board对象的指针,因此需要将代码更改为 -

  #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;
}