调用函数时,私有类变量不会更改

  • 本文关键字:类变量 函数 调用 c++
  • 更新时间 :
  • 英文 :


当我尝试在 FBullCowGame.h 中更改我的 2 个私有类变量时,我遇到了问题。似乎构造函数正在调用函数 Reset(( [位于 FBullCowGame.cpp] 但 Reset(( 函数不会更改整数 MyMaxTry 和 MyCurrentTry.我是 c++ 的新手,所以可能这是显而易见的,但我找不到它。

这是主要的.cpp

#include <iostream>
#include <string>
#include "FBullCowGame.h"
using FText = std::string;
void PrintIntro();
void PlayGame();
FText GetGuess();
FText PrintGuess();
FBullCowGame BCGame;//Dodeljujemo naziv u main-u FBullCowGame-u , takodje ako ima neki kod u constructoru on ga izvrsava pri ovaj deklaraciji

bool AskToPlayAgain();

int main() 
{
bool bPlayAgain = false;
do {
PrintIntro();
PlayGame();
bPlayAgain = AskToPlayAgain();
}
while (bPlayAgain);
return 0;
}
void PrintIntro()
{
//Define constant var
constexpr int WORD_LENGHT = 6;
//Welcome to the player and asking the guess
std::cout << "Welcome to Bulls and Cowsn";
std::cout << "Can you guess my " << WORD_LENGHT;
std::cout << " letter isogram word?n";
}
void PlayGame()
{
BCGame.Reset();
int MaxTries = BCGame.GetMaxTries();
//Looping for guesses
for (int i = 1; i <= MaxTries; i++)
{
FText Guess = GetGuess();
//Repeat the guess back to them
std::cout << "Your guess is: " << Guess << std::endl;
std::cout << std::endl;
}
return;
}
FText GetGuess()
{
int CurrentTry = BCGame.GetCurrentTry();
//Player enters their guess
std::cout << std::endl << "Try " << CurrentTry << ".What is your guess?n";
FText Guess = "";
std::getline(std::cin, Guess);
return Guess;
}
bool AskToPlayAgain()
{
FText Response = "";
std::cout << "Do you want to play again (y/n) ?" << std::endl;
std::getline(std::cin, Response);
return (Response[0] == 'y') || (Response[0] == 'Y');

}

FBullCowGame.h/

#pragma once
#include <string>
class FBullCowGame {
public:
FBullCowGame();//Constructor izvrsava se kod u njemu pri deklaraciji BCGame u nasem slucaju

int GetMaxTries() const;
int GetCurrentTry()const;
bool IsGameWon()const;
void Reset();
bool CheckGuessValidity(std::string);

private:
//Compile time values gets overwritten by run time values in Constructor
int MyMaxTries;
int MyCurrentTry;

};

还有牛游戏.cpp/

#include "FBullCowGame.h"
FBullCowGame::FBullCowGame()
{
//Run time values
Reset();
}
void FBullCowGame::Reset()
{
constexpr int MAX_TRIES = 8;
int MyMaxTries = MAX_TRIES;
int MyCurrentTry = 1;
return;
}
int FBullCowGame::GetMaxTries ()const
{
return MyMaxTries;
}
int FBullCowGame::GetCurrentTry ()const
{
return MyCurrentTry;
}
bool FBullCowGame::IsGameWon ()const
{
return false;
}
bool FBullCowGame::CheckGuessValidity(std::string)
{
return false;
}

您正在使用恰好具有完全相同名称的函数局部变量来隐藏成员变量。

void FBullCowGame::Reset()
{
constexpr int MAX_TRIES = 8;
int MyMaxTries = MAX_TRIES;
int MyCurrentTry = 1;
return;
}

只需分配给成员变量,但不要重新声明它们

void FBullCowGame::Reset()
{    
constexpr int MAX_TRIES = 8;
MyMaxTries = MAX_TRIES;
MyCurrentTry = 1;
}

最新更新