首页 > 解决方案 > 尝试将用户定义类型的向量插入用户定义类型向量

问题描述

我正在尝试在咒语系统中为小型 RPG 战斗模拟制作矢量矢量。我想要完成的主要目标是拥有一个玩家可以访问的法术向量并选择他们想要施放的法术类型:火、冰等,然后选择法术的名称:燃烧、冰霜、等等

下面的代码就是我将 Spell 和 FireSpell 声明为的代码。我正在尝试将 FireSpells 向量插入到向量法术类型的向量中,但是它没有插入。有没有办法让它插入?

我已经尝试将 FireSpell 上的 push_back 放入 Spells 向量中,它工作正常,但是,当我将 FireSpell 向量 push_back 到向量 Spell 类型的向量中时,它总是返回错误。

魔法.h

struct Fire
{
    int damage;
    int dps;
}; 

struct Spell
{
    int cost;
    string name;
};

struct FireSpell : Spell, Fire
{

};

魔术.cpp

#include <iostream>
#include "MagicSys.h"
#include <vector>
#include <string>
#include "Magic.h"

using std::cout;
using std::vector;

FireSpell burn;
FireSpell inferno;
FireSpell volcano;


int mainfunc()
{
    vector<vector<Spell>> PlayerSpells;
    vector<FireSpell> PlayerFSpells;
    PlayerFSpells.push_back(burn);
    PlayerFSpells.push_back(inferno);
    PlayerFSpells.push_back(volcano);

 /*Trying to insert FireSpell Vector into the end of the vector of Spell vectors*/

    PlayerSpells.push_back(PlayerFSpells);

    vector<vector<Spell>>::iterator it;
    for (it = PlayerSpells.begin(); it!=PlayerSpells.end(); ++it)
        cout << &it << " ";

    return 0;
}

我希望内部 FireSpell 向量插入到行上的外部 Spell 向量中:PlayerSpells.push_back(PlayerFSpells);但是,它给了我错误消息:

no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back
[with _Ty=std::vector<Spell, std::allocator<Spell>>,
_Alloc=std::allocator<std::vector<Spell, std::allocator<Spell>>>]"
matches the argument list

标签: c++structclass-designgame-development

解决方案


如果您来自其他一些语言,您可能习惯于将可变值视为隐式引用。在这些语言中,您通常能够轻松构建不同类型的集合,这些集合可能共享也可能不共享接口,并且您可能会或可能不会对它们进行多态处理(后期绑定)。

然而,在 C++ 中,对象不是引用:它们是内存中的实际对象,这要求它们具有编译时已知的大小。但是,您仍然可以通过指针或引用轻松创建多态集合,甚至可以拥有没有公共接口的对象集合;但你必须明确这一点——并了解语言规则以防止像切片这样的陷阱(例如,参见什么是对象切片?)。


推荐阅读