【发布时间】:2021-04-06 06:03:55
【问题描述】:
#include <iostream>
#include <string>
#include <vector>
class Enemy
{
private:
std::string rank = "Boss";
std::string rank2 = "Miniboss";
public:
std::string type;
std::string get_rank(){
return rank;
}
std::string get_rank2(){
return rank2;
}
};
int add_enemy(std::vector<Enemy>&enemies, Enemy enemy) // I wanna pass by reference because I want to modify the vector
{
for(size_t i; i < enemies.size(); i++) {
if(enemies.at(i).type == enemy.type){ // here I'm saying, if I add an enemy that's of the same type, I don't wanna add it anymore
return 1; // it returns an error, because they are the same type, so it shouldn't add it?
}
}
enemies.push_back(enemy);
}
int main()
{
Enemy enemy;
enemy.type = "Dragon";
std::cout << enemy.type << " is a " << enemy.get_rank() << std::endl;
Enemy nrone, nrtwo, nrthree, nrfour, nrfive;
// I want to add these and keep them in a vector
std::vector<Enemy> enemies;
nrone.type = "Orc";
nrtwo.type = "Goblin";
nrthree.type = "Troll";
nrfour.type = "Ogre";
nrfive.type = "Orc";
std::cout << nrfour.type << " is of rank " << nrfour.get_rank2() << std::endl;
enemies.push_back(nrone);
enemies.push_back(nrtwo);
enemies.push_back(nrthree);
enemies.push_back(nrfour);
enemies.push_back(nrfive);
std::cout << add_enemy(enemies, enemy) << std::endl;
return 0;
}
嗨,我现在正在研究 C++ 中的类和对象,我正在尝试实现以下目标:创建一个 NPC 怪物向量并将一堆怪物类型添加到向量中。但是,如果怪物/敌人属于同一类型,我不想将其添加到向量中,而是将其丢弃。
在我的例子中,我有两个兽人,所以向量应该丢弃其中一个兽人,但它没有,而是在屏幕上显示一个奇怪的数字。
我尝试过这种方式,但我仍然无法弄清楚:(有什么解决方案吗?
【问题讨论】:
-
您可能想要
std::unordered_set<Enemy>而不是std::vector<Enemy>。std::vector<Enemy>显然不像你想象的那样工作。 -
你必须编写它的构造函数来用默认值初始化数据成员。
标签: c++ class oop vector c++17