C ++更新/更改来自不同类/变量的变量

时间:2015-09-16 19:09:52

标签: c++ class variables

我是C ++的noobie,我正在为Visual Studios上的练习制作一个游戏,但是当我添加exp时,我无法弄清楚如何更新统计数据。我尝试通过添加exp来改变玩家等级但是当我添加55 exp时,玩家仍然保持在等级1。

主:

    #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 个答案:

答案 0 :(得分:1)

如果向exp添加55,则只会更改exp。

您可以编写getter和setter并将成员变量声明为private:

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...

并在main.cpp中使用addExp()方法。

将成员变量设为私有的一个好处是,您可以更好地控制它们的操作方式。例如。如果您添加exp,则可以同时设置level