c++ - 离开类文件时变量重置
问题描述
我正在通过制作刽子手游戏来练习 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();
}
在类外调用短语变量时,我希望它返回设置的短语。相反,它返回默认的空值。
编辑:谢谢你的帮助!答案在他的评论中,并且代码现在正在运行(我没有正确地通过引用传递)。
解决方案
我有另一个 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
推荐阅读
- docker - 如何在不使用 Docker compose 的情况下将 docker 应用程序部署到生产环境?
- html - 如何在背景上渲染整个图像?
- algorithm - 最小化二叉树范围和的内存消耗和执行时间
- javascript - 如何格式化数据堆叠的highchart?
- docker - Docker 绑定挂载目录与命名卷性能对比
- c++ - 使用 IOCTL 将音频数据从用户模式发送到 Sysvad(虚拟音频驱动程序)
- window - 如何使用 C++ 在 Windows 10 中捕获窗口
- pytorch - RuntimeError: Expected hidden[0] size (1, 1, 512), got (1, 128, 512) for LSTM pytorch
- python-3.x - 如何创建包含具有均匀随机分布的连续值和分类值的特定大小的数据框
- nuget - 微软的“....抽象”Nuget 包的想法是什么?