gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:04:49 24 4
gpt4 key购买 nike

我是 C++ 的菜鸟,当时我正在 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;
}
}
}

游戏.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 << " ";
}

游戏.h:

#pragma once
#include "Player.h"

class Game {
public:
Game();
};

播放器.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));
}

播放器.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));

};

最佳答案

如果将 exp 加 55,则只有 exp 会发生变化。

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

播放器.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() 方法。

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

关于C++更新/更改来自不同类/变量的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32616794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com