2017-04-12 33 views
1

我正在關注udemy.com上的一個名爲「虛幻引擎開發者課程」的教程,而且我被困在C++部分的某個部分。我創建了一個具有構造函數的對象來初始化我的變量,它的工作原理當我在構造函數運行時打印變量時,我得到了預期的行爲,但是當我在使用getter的程序中輸出變量時,值是始終爲0。請幫助=)使用前重置會員變量

FBullCow.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; 
}; 

的main.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 game\n"; 
    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; 
} 

回答

1

在該方法中:

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; 
} 

它應該現在工作。請注意,你的編譯器應該已經告訴你有關被初始化但未被使用的變量。