成员变量在使用前重置
Member variables resetting before use
我正在学习一个名为"虚幻引擎开发者课程"的 udemy.com 教程,我被困在C++部分的某个部分。
我创建了一个带有构造函数的对象来初始化我的变量,它可以工作,当我在构造函数运行时打印变量时,我得到了预期的行为,但是当我在程序中使用 getter 输出变量时,值始终为 0。请帮忙=(
牛.cpp
#include "FBullCow.h"
FBullCow::FBullCow()
{
Reset();
}
void FBullCow::Reset()
{
constexpr int MAX_TRIES = 8;
int MyCurrentTry = 1;
int MyMaxTries = MAX_TRIES;
return;
}
int FBullCow::GetMaxTries() const
{
return MyMaxTries;
}
int FBullCow::GetCurrentTry() const
{
return MyCurrentTry;
}
bool FBullCow::IsGameWon() const
{
return false;
}
bool FBullCow::CheckGuessValidity(std::string) const
{
return false;
}
FBullCow.h
#pragma once
#include <string>
class FBullCow
{
public:
FBullCow();
void Reset();
int GetMaxTries() const;
int GetCurrentTry() const;
bool IsGameWon() const;
bool CheckGuessValidity(std::string) const;
private:
int MyCurrentTry;
int MyMaxTries;
};
主.cpp
#include <iostream>
#include <string>
#include "FBullCow.h"
void intro();
std::string GetGuess();
void PlayGame();
bool AskToPlayAgain();
FBullCow BCGame;
int main()
{
//Introduce the game
intro();
do
{
//Play the game
PlayGame();
}
while (AskToPlayAgain() == true);
return 0;
}
void intro ()
{
//Introduce the game
constexpr int WORD_LENGTH = 5;
std::cout << "Welcome to my bull cow gamen";
std::cout << "Can you gues the " << WORD_LENGTH << " letter isogram I'm thinking of?n";
return;
}
std::string GetGuess()
{
std::string Guess = "";
std::cout << "You are on try " << BCGame.GetCurrentTry() << std::endl;
std::cout << "Enter your guess: ";
std::getline(std::cin, Guess);
return Guess;
}
void PlayGame()
{
std::cout << BCGame.GetMaxTries() << std::endl;
std::cout << BCGame.GetCurrentTry() << std::endl;
int MaxTries = BCGame.GetMaxTries();
//Loop for the number of turns asking for guesses
for(int i = 0; i < MaxTries; i++)
{
std::string Guess = GetGuess();
//Get a guess from the player
//Repeat guess back to them
std::cout << "Your guess was " << Guess << std::endl;
}
}
bool AskToPlayAgain()
{
std::cout << "Do you want to play again? Y or N: ";
std::string response = "";
std::getline(std::cin, response);
if(response[0] == 'y' || response[0] == 'Y')
{
return true;
}
return false;
}
在方法中:
void FBullCow::Reset()
{
constexpr int MAX_TRIES = 8;
int MyCurrentTry = 1;
int MyMaxTries = MAX_TRIES;
return;
}
在这里,您设置的是局部变量,而不是成员变量。只需删除int
部分:
void FBullCow::Reset()
{
constexpr int MAX_TRIES = 8;
MyCurrentTry = 1;
MyMaxTries = MAX_TRIES;
return;
}
它现在应该可以工作了。请注意,编译器应该警告您正在初始化但未使用的变量。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- C++预处理会生成变量成员、资源库和映射
- 局部堆栈变量成员的返回值优化
- Google Mock:在目标类的构造函数中实例化的模拟私有变量成员
- 使用指向结构变量成员的指针访问该结构的成员的地址
- 如果派生类仅包含自动变量成员,是否有必要具有虚拟驱动器
- 线程安全性和静态变量/成员功能
- "static const char array"可以在 C 语言上包含变量成员吗
- 仅用于内部目的的类的所有变量/成员的技术术语是什么
- 如何强制转换变量成员以将其作为函数的引用参数传递
- 类中未声明变量成员函数
- 在 main 中初始化类的 "static const" 类型变量成员的更好方法
- c++模板类静态const变量成员作为映射键给出未定义引用
- 在类中初始化结构变量成员会导致分割错误
- 在c++中建模变量成员类型
- 模板私有静态变量成员的未定义符号
- 不能访问公共静态变量成员
- 常量变量成员在C++有什么用?
- g++ 4.8.2坚持简单变量成员是数组