在C++中使用类时函数"未在此范围内声明"

Function 'not declared in this scope' when using class in C++

本文关键字:声明 范围内 函数 C++      更新时间:2023-10-16

我正在尝试制作一个基本程序,该程序允许用户在奥赛罗(Othello)互相播放,现在我只是在尝试初始化一个代表木板并显示它的空白阵列。我已经与课程合作了几次,而且我的代码似乎与我所做的其他类别没有什么不同,但是我找不到为什么我的功能没有正确声明。错误是:

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();
}

我也知道全局变量不是最大的变量,但是我们被指示使用板尺寸的全局变量。

为了能够调用othelloboard.cpp中实现的方法,您必须在main()内部创建一个类型othelloboard的对象,然后您只需使用objectName.methodName()调用方法。基本上,您必须执行以下操作:

  1. 创建类型othelloboard的对象:

    othelloboard ob;

  2. 使用

    调用您的方法

    ob.generateBoard();

etc