我確信有一個簡單的解決方案,但我無法確定最佳選擇是什么。例如,我有一個名為 entity 的類,它看起來像這樣:
class Entity
{
public:
int health;
int strength;
};
這顯然是一個非常簡單的類,但我的問題是在創建每個物件時。如果我正在嘗試制作游戲或任何我有許多不同型別的物體的游戲,這些物體具有不同的健康和力量值。組織所有這些變數的宣告的最佳方法是什么,這樣我就不會得到如下所示的內容:
Entity cat;
cat.health = 6;
cat.strength = 10;
Entity dog;
dog.health = 10;
dog.strength = 15;
Entity wolf;
wolf.health = 17;
wolf.strength = 25;
這看起來已經有點亂了,但是隨著物件的增多或要宣告的變數更多的物件,情況會變得更糟。解決此類問題的最佳方法是什么,我一直在努力弄清楚。
uj5u.com熱心網友回復:
您正在尋找的答案是封裝。您可以嘗試以下方法,而不是讓所有變數都公開并一個一個地為它們分配值:
class Entity
{
private: int health;
private: int strength;
public:
Entity(int h, int s) //constructor
{
health = h;
strength = s;
}
};
然后像這樣呼叫它:
Entity cat(15,16);
您也可以使用單獨的 setter 函式,但建構式是最簡單的方法。
uj5u.com熱心網友回復:
只要 Entity 類保持簡單并且不需要自定義建構式用于其他目的,您就可以像這樣初始化物件:
Entity cat { .health = 9, .strength = 2 };
Entity dog { .health = 1, .strength = 3 };
與建構式方法相比,這可能更具可讀性,因為您保留了變數名。
uj5u.com熱心網友回復:
要存盤許多要使用的物件container。由于您的物件由名稱、 和 標識,dog因此cat可以wolf使用映射:
#include <string>
#include <map>
#include <iostream>
struct Entity {
int health;
int strength;
};
int main() {
std::map<std::string,Entity> entities;
entities["cat"] = {6,10};
entities["dog"] = {10,15};
entities["wolf"] = {17,25};
for (const auto& e : entities){
std::cout << e.first << " health: " << e.second.health << " strength: " << e.second.strength << "\n";
}
}
輸出:
cat health: 6 strength: 10
dog health: 10 strength: 15
wolf health: 17 strength: 25
使用字串作為鍵不一定是最好的選擇,它只是為了演示可以做什么。例如,如果物體的數量是固定的,您可以使用enum entity_type { dog,cat,wolf}as 鍵。或者,名稱可以是成員,Entity您可以使用 astd::vector<Entity>來存盤它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/428606.html
