功能'未在此范围内声明'在C ++中使用类时

时间:2016-11-27 19:30:16

标签: c++

我试图制作一个允许用户在othello中互相玩耍的基本程序,而现在我只是尝试初始化一个代表棋盘并显示它的空白数组。我已经和几次课程一起工作了,而且我的代码似乎与我已经制作的其他课程有所不同,但是我无法找到为什么我的职能不是&#39 ; t正确宣布。错误是:

othello.cpp: In function ‘int main()’:
othello.cpp:9:17: error: ‘generateBoard’ was not declared in this scope
   generateBoard();
             ^
othello.cpp:10:13: error: ‘addBorder’ was not declared in this scope
   addBorder();
         ^
othello.cpp:11:18: error: ‘displayOthello’ was not declared in this
   scope
   displayOthello();
              ^
make: *** [othello.o] Error 1

这是othelloboard.h

const int boardSize = 4;

class othelloboard{
  public:
    othelloboard();
    ~othelloboard();
    void generateBoard();
    void addBorder();
    void displayOthello();

  private:
    char othelloArray[boardSize][boardSize];
};

这是othelloboard.cpp

#include <iostream>
using namespace std;

#include "othelloboard.h"

//Initialize global variables
extern const int boardSize;

othelloboard::othelloboard(){}
othelloboard::~othelloboard(){}

void othelloboard::generateBoard(){
  for (int i=1; i<= boardSize; i++){
    for (int j=1; j<= boardSize; j++){
      othelloArray[i][j] = '.';
    }
  }
}

void othelloboard::addBorder(){
  for (int i=1; i<= boardSize; i++){
    char temp = (char)i + '0';
    othelloArray[0][i] = temp;
    othelloArray[i][0] = temp;
  }
}

void othelloboard::displayOthello(){
  for (int i=0; i<= boardSize; i++){
    for (int j=0; j<= boardSize; j++){
      cout << othelloArray[i][j];
    }
    cout << endl;
  }
}

这是Othello.cpp

#include <iostream>
using namespace std;

#include "othelloboard.h"

int main(){
  extern const int boardSize;
  cout << boardSize << endl;
  generateBoard();
  addBorder();
  displayOthello();
}

我也知道全局变量并不是最大的,但我们被指示使用全局变量作为电路板大小。

1 个答案:

答案 0 :(得分:0)

为了能够调用othelloboard.cpp中实现的方法,您必须在othelloboard内创建main()类型的对象,然后您只需使用{{1}调用方法}。基本上你必须做以下事情:

  1. 创建objectName.methodName()类型的对象:

    othelloboard

  2. 使用

    调用您的方法

    othelloboard ob;