[英]C++ Pointers In A Game
我似乎永遠無法理解指針。 我終於有了一個使用指針的工作代碼,以創建一個快速的角色和敵人,然后模擬一個過於簡單的戰斗。 它似乎可以100%正常運行,但是我不確定100%正確或我做對了。 到目前為止,我已經在我的C ++書中閱讀了13章(其中2章專門針對指針),但是我仍然不確定它是否被單擊。 如果這看起來像是對它們的有效使用和正確利用,我想我已經到達了,只是想澄清一下。 提前致謝!
#include <iostream>
#include <string>
#ifndef CLASS_H
#define CLASS_H
class Unit
{
public:
Unit(const std::string name, int hp, int power);
~Unit();
void printHP();
void attack(Unit* unit);
bool isDead();
private:
std::string mName;
int mHP;
int mPower;
};
Unit::Unit(const std::string name, int hp, int power)
{
mName = name;
mHP = hp;
mPower = power;
}
void Unit::printHP()
{
std::cout << std::endl;
std::cout << mName << "'s HP: " << mHP << std::endl;
}
void Unit::attack(Unit* unit)
{
std::cout << std::endl;
std::cout << unit->mName << " takes " << this->mPower << " damage! " << std::endl;
unit->mHP -= this->mPower;
}
bool Unit::isDead()
{
return this->mHP < 1;
}
Unit::~Unit()
{
}
#endif
int main()
{
Unit player1("GoodFellow", 20, 5);
Unit Enemy("ABadMan", 10, 2);
while (!Enemy.isDead())
{
player1.printHP();
Enemy.printHP();
player1.attack(&Enemy);
Enemy.attack(&player1);
}
}
修改為此...我想我得到僅使用引用的原因,只是試圖獲得指針的概念。
#include <iostream>
#include <string>
#ifndef CLASS_H
#define CLASS_H
class Unit
{
public:
Unit(const std::string name, int hp, int power);
~Unit();
void printHP();
void attack(Unit& unit);
bool isDead();
void setHP(int hp);
private:
std::string mName;
int mHP;
int mPower;
};
Unit::Unit(const std::string name, int hp, int power)
{
mName = name;
mHP = hp;
mPower = power;
}
void Unit::printHP()
{
std::cout << std::endl;
std::cout << mName << "'s HP: " << mHP << std::endl;
}
void Unit::attack(Unit& unit)
{
std::cout << std::endl;
std::cout << unit.mName << " takes " << this->mPower << " damage! " << std::endl;
unit.mHP -= this->mPower;
}
bool Unit::isDead()
{
return this->mHP < 1;
}
void Unit::setHP(int hp)
{
this->mHP = hp;
}
Unit::~Unit()
{
}
#endif
int main()
{
Unit player1("GoodFellow", 20, 5);
Unit Enemy("ABadMan", 10, 2);
while (true)
{
while (!Enemy.isDead())
{
player1.printHP();
Enemy.printHP();
player1.attack(Enemy);
Enemy.attack(player1);
}
char playAgain;
std::cout << "Fight again? (y)/(n)" << std::endl;
std::cin >> playAgain;
if (playAgain == 'n')
{
break;
}
else
{
Enemy.setHP(10);
}
}
}
是的,這是對指針的合理使用。 實際上,我很高興看到您很少使用它們。 我一半期望看到Unit* player1 = new Unit ...
都是這樣。 但是,不,您使用了自動存儲持續時間(而不是動態),這非常合適。
因此,將Unit*
傳遞給attack
功能的主要原因是在該功能內部,您可以修改要攻擊的Unit
並在外部看到效果。 如果要直接傳遞Unit
,則將它們復制到函數中,然后復制到unit->mHP -= this->mPower;
只會影響副本。
但是,這里有一個更合適的工具可供您使用。 您可以使用引用 。 引用還允許您傳遞對象而不復制它,以便可以在外部看到函數內部的修改。 您的攻擊功能簽名將變為:
void Unit::attack(Unit& unit)
Unit&
類型是“對Unit
引用”。 不要將&
的使用&
對象的地址混為一談-這意味着這里的東西完全不同。 然后,您可以這樣稱呼它:
player1.attack(Enemy);
關鍵是您應盡量避免使用指針。 由於您可以在此處使用更安全的引用(無需檢查null
),因此應使用它們。
了解指針如何工作是很好的,但是在這樣做時,您應該學習如何使用其他更合適的工具來完成工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.