【问题标题】:private member data not being available to public member function [closed]公共成员功能无法使用私有成员数据[关闭]
【发布时间】:2020-06-09 21:15:29
【问题描述】:

我有下面的代码。

当我有主 Run() 函数时,运行 ResetTrackingTable() 函数。 ResetTrackingTable() 为 my_n_rows 和 my_n_cols 调用 0,而不是访问存储在私有成员数据中的现有数字。

这是为什么呢?似乎它正在创建函数的新实例......


public:

    WordGame();


    void Run(Board &gameBoard, Trie &library, int wordlengthlim);

    void CheckNode(int row, int col, Board & gameBoard, Trie &Library);

    void ExitNode();
    void ResetTrackingTable(int rows, int cols); 

    void PrintWordList();



private:
    std::vector<std::string> my_WordList;
    int my_wordlength; 
    int my_wordlengthlimit;
    std::stringstream currentword; 

    int my_n_cols;
    int my_n_rows;

    std::vector<std::vector<bool>> my_TrackingTable;
};



void WordGame::Run(Board & gameBoard, Trie &Library, int wordlengthlim)
{

    //std::stringstream word;
    //std::string tempword;
    //word.str("");

    currentword.str(""); //Clear current word

    int my_wordlengthlimit = wordlengthlim; //Import limit word length
    int my_wordlength = 0; //Set current word length

    int my_n_rows = gameBoard.numRows(); //Import number of rows
    int my_n_cols = gameBoard.numCols(); //Import number of cols

    for (int i_row = 0; i_row < my_n_rows; ++i_row)
    {
        for (int i_col = 0; i_col < my_n_cols; ++i_col)
        {
            //Actually, when should it be reset?
            this->ResetTrackingTable(); //Initialize the tracking table as all false before each new starting char. 

            CheckNode(i_row, i_col,gameBoard,Library); //Check each beginning node. 
        }
    }
}

void WordGame::ResetTrackingTable()
{

    for (int i_row = 0; i_row < my_n_rows; ++i_row)
    {
        my_TrackingTable.push_back(std::vector<bool> {false});

        for (int i_col = 1; i_col < my_n_cols; ++i_col)
        {
            my_TrackingTable[i_row].push_back(false);  //Initialize the tracking table as all false.
        }
    }

}

【问题讨论】:

  • int my_n_rows = is not assignment a member variable is created an local one

标签: c++ member-functions


【解决方案1】:

这些代码行:

int my_n_rows = gameBoard.numRows(); //Import number of rows
int my_n_cols = gameBoard.numCols(); //Import number of cols

Run 函数中声明新变量。

如果您想改为引用成员变量,请删除 int 声明符:

my_n_rows = gameBoard.numRows(); //Import number of rows
my_n_cols = gameBoard.numCols(); //Import number of cols

您需要对所有要使用的成员变量执行此操作。

另外,你的声明:

void ResetTrackingTable(int rows, int cols); 

不符合其定义:

void WordGame::ResetTrackingTable() { // ...

你需要有相同数量的相同类型的参数。

【讨论】:

  • 可能还想提一下ResetTrackingTable 应该用两个参数调用?
猜你喜欢
  • 2013-07-07
  • 2014-08-21
  • 1970-01-01
  • 2014-04-22
  • 2012-10-06
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多