2015-09-16 125 views
0

我是C++的noobie,我在Visual Studios上製作了一個遊戲練習遊戲,我無法弄清楚如何在添加exp時更新統計信息。我試圖通過添加exp來改變玩家等級,但是當我添加55 exp時,玩家仍然保持在等級1。C++更新/更改來自不同類/變量的變量

主要:

#include <iostream> 
    #include <windows.h> 
    #include "Game.h" 

using namespace std; 

void FalseLoad(); 

int main() { 
    //Cool load intro 
    FalseLoad(); 
    cout << "\n \n"; 

    Game::Game(); 

    system("PAUSE"); 

    return 0; 
} 

void FalseLoad() { 
    int i = 0; 
    int start; 

    cout << "***Freelancer*** \n \n"; 

    system("PAUSE"); 

    while (i <= 100){ 
     cout << "Loading game... " << i << "% \n"; 
     i++; 
     Sleep(110 - i); 
     if (i == 100) { 
       start = 0; 
     } 
    } 
} 

Game.cpp:

#include <iostream> 
#include "Game.h" 

using namespace std; 

Game::Game() { 
    Player Player; 

    Player.Init(); 

    cout << Player.exp << " " << Player.level; 
    Player.exp += 55; 
    cout << " " << Player.exp << " " << Player.level << " "; 
} 

Game.h:

#pragma once 
#include "Player.h" 

class Game { 
public: 
    Game(); 
}; 

Player.cpp:

#include "Player.h" 

Player::Player() { 

} 

void Player::Init() { 
    int exp = 5; 
    int level = (exp/5); 
    int attack = (10 + (level * 2)); 
    int defense = (10 + (level * 2)); 
    int speed = (10 + (level * 2)); 
} 

Player.h:

#pragma once 
class Player 
{ 
public: 
    Player(); 

    void Init(); 

    int exp = 5; 
    int level = (exp/5); 
    int attack = (10 + (level * 2)); 
    int defense = (10 + (level * 2)); 
    int speed = (10 + (level * 2)); 

}; 
+1

顯示的所有這些初始化都是無意義的,除非使用'const'表達式。 –

回答

1

如果你添加55到exp,只有exp會被改變。

你可以寫getter和setter和聲明的成員變量私人:

Player.h

#pragma once 
class Player 
{ 
public: 
    Player(); 

    void Init(); 

    void addExp(const int additionalExp); 
    int getExp(); 

    //... TODO add similar get/set methods for the other members... 

private: 
    int exp = 5; 
    int level = (exp/5); 
    int attack = (10 + (level * 2)); 
    int defense = (10 + (level * 2)); 
    int speed = (10 + (level * 2)); 
}; 

,並添加方法的定義:

#include "Player.h" 

Player::Player() { 

} 

void Player::Init() { 
    int exp = 5; 
    int level = (exp/5); 
    int attack = (10 + (level * 2)); 
    int defense = (10 + (level * 2)); 
    int speed = (10 + (level * 2)); 
} 

void Player::addExp(const int additionalExp) { 
    if (additionalExp < 0) return; // think about error handling or use 
            // unsigned for exp 
    exp += additionalExp; 
    level = exp/50; // or something else, as you like. 
} 

int Player::getExp(){ return exp; } 

// ... TODO add definitions for the other get/set methods... 

,並使用addExp()方法你的main.cpp。

讓成員變量變爲私有的一個好處是您可以更好地控制它們的操作方式。例如。如果添加exp,則可以同時相應地設置level