如何在AnoteHR CPP文件中的另一个函数上使用CPP文件的函数中的变量

How do I use a variable from a function of a cpp file on another function in anotehr cpp file?

本文关键字:文件 函数 CPP 变量 另一个 AnoteHR      更新时间:2023-10-16

我正在制作一个俄罗斯方块游戏,我不知道如何使用将分数打印到屏幕上的另一个文件中计算得分的变量。这是代码:

//board.cpp
//Here is the variable mScore that i want to use
/* 
======================================                                  
Delete all the lines that should be removed
====================================== 
*/
int Board::DeletePossibleLines ()
{
     int Score = 0;
     for (int j = 0; j < BOARD_HEIGHT; j++)
     {
         int i = 0;
         while (i < BOARD_WIDTH)
         {
            if (mBoard[i][j] != POS_FILLED) break;
            i++;
         }
         if (i == BOARD_WIDTH)
         {
             DeleteLine(j);
             Score++;
         }
     }
     int mScore = Score;
     return mScore;
 }

它在董事会中的班级中声明为:

//Board.h
class Board
    {
    public:
    int DeletePossibleLines();
    }

我想在io.cpp中使用它,我将其特雷德(

//IO.cpp
#include "Board.h"
void IO :: text()
    {
    //I call the class
    Board *mBoard
    //I attribute the function to a variable and i get an error
    int Score = *mBoard -> DeletePossibleLines;
    }

我遇到的错误是"错误C2276:'*':在io.cpp

上绑定的成员函数表达式上的非法操作

所以我想从io.cpp的得分等于board.cpp

的MSCORE。

如果有帮助,这也是我尝试和失败的方法:

我试图在io.cpp中声明类:

  //IO.cpp
  Board mBoard
  mBoard.DeletePossibleLines

,但出现一个错误,上面说"表达必须具有类型"

我也尝试将所有内容都放在同一文件中,但是我也失败了,加上每个文件都有一百行代码。

您必须调用该功能,而不是分配函数的指针。使用这样的东西:

int Score = mBoard -> DeletePossibleLines();
//                                       ^^ note these!

这是一个有效的mBoard指针,该指针在您发布的代码中不存在。

mBoard是指向Board对象的指针。假设它是正确初始化的(这是您的摘要中缺少的),则无需使用它来调用其方法。此外,您缺少括号(())来表示这是一个方法调用,而不是公共数据成员:

int Score = mBoard -> DeletePossibleLines();