首页 > 解决方案 > 离开类文件时变量重置

问题描述

我正在通过制作刽子手游戏来练习 C++。问题是当我在一个类文件中设置刽子手词然后移动到另一个类文件时,我发现它已经被重置了。当我调用变量时,它是空的。

我尝试使用引用而不是标准变量,因为我知道当您调用函数时,它只会创建变量的副本。我有另一个 buildGame.h 和 buildGame.cpp 文件,但他们所做的只是调用 getPhrase(); 功能。这是我发现变量被重置的地方,并且不包含短语值。

这是我的 main.cpp 文件:v

#include "genGame.h"
#include "buildGame.h"

int main(){
    genGame startGame;
    buildGame build;
    startGame.genPhrase();
    buildGame();
    return 0;
}

这是我的 genGame.h 文件:v

#ifndef GENGAME_H
#define GENGAME_H
#include <string>

class genGame{
    public:
        genGame();
        void genPhrase();
        std::string getPhrase() const;

    private:
        std::string phrase;
        int randnumb;
};

#endif

这是我的 gengame.cpp 文件:v

#include "genGame.h"
#include <iostream>
#include<time.h>
#include <fstream>
using namespace std;

genGame::genGame(){}

string genGame::getPhrase() const{
    cout << phrase << endl;     //included for testing purposes
    return phrase;
}

void genGame::genPhrase(){
    cout << "Welcome to hangman!" << endl;
    string& phraseRef = phrase;     //tried setting a reference to change the variable itself, not just the copy
    srand(time(0));
    randnumb = rand() % 852 + 1;    //random number to determine which word will be pulled out of 852 words
    ifstream wordlist ("wordlist.txt");     //list of hangman words

    if (wordlist.is_open()){
        for (int i = 1; i <= randnumb; i++){
            getline(wordlist, phraseRef);       //get the word, set it equal to the phrase variable
        }
        wordlist.close();
    }

    cout << phraseRef << endl;      //output word choice for testing purposes
    cin.get();

}

在类外调用短语变量时,我希望它返回设置的短语。相反,它返回默认的空值。

编辑:谢谢你的帮助!答案在他的评论中,并且代码现在正在运行(我没有正确地通过引用传递)。

标签: c++

解决方案


我有另一个 buildGame.h 和 buildGame.cpp 文件,但他们所做的只是调用 getPhrase(); 功能。这是我发现变量被重置的地方,并且不包含短语值。

使用您当前编写的代码,我什至不需要查看buildGame课程即可回答。您在其中创建的两个buildGame对象(†)main中的任何一个都不可能了解在 中创建的genGame对象main

如果您需要将对象标识为对对象startGame中的成员函数或类似buildGame对象可用,则需要将其作为引用传递。例如,您可能有这个:

void buildGame::play(const genGame &startGame)
{
    std::cout << "Playing with phrase: " << startGame.getPhrase() << std::endl;
}

在 中main,您可能会这样做:

int main()
{
    genGame startGame;
    buildGame build;
    startGame.genPhrase();
    build.play(startGame);  // <=== pass reference to startGame
    return 0;
}

然而,您认为您是startGame在原始代码中访问,您错了。


(†) :是的,您创建了两个buildGame对象:

buildGame build;  // This constructs a buildGame identified as 'build'
buildGame();      // This constructs a buildGame and then destroys it

推荐阅读