您好,我遇到了一个问题,我找不到解决方案。我正在创建一个实体 - 带有智能指针的组件系统。
我得到的错误是:
a reference of type
std::unique_ptr<PrimaryComponent, std::default_delete<PrimaryComponent>> &
(not const-qualified) cannot be initialized with a value of typestd::unique_ptr<PlayerGraphics, std::default_delete<PlayerGraphics>>
游戏世界类:
auto GameWorld::Setup_World() -> void
{
player->Attach_Component(player_Graphics);
Add_GameObject(player);
}
游戏对象类附加组件函数:
void GameObject::Attach_Component(std::unique_ptr<PrimaryComponent> &component)
{
if (component != nullptr)
{
component_container.push_back(component);
}
}
player_Graphics和player的声明:
class GameWorld
{
private:
std::vector<std::unique_ptr<GameObject>> gameObject_List;
std::unique_ptr<GameObject> player;
std::unique_ptr<PlayerGraphics> player_Graphics
player
是 GameObject
, player_Graphics
是一个派生自 PrimaryComponent
的图形组件.
主要组件类:
class PrimaryComponent
{
protected:
public:
PrimaryComponent();
virtual ~PrimaryComponent();
virtual void Render(GameObject &gameObject) = 0;
virtual void Update(GameObject &gameObject, GameWorld &gameWorld, float gameTime) = 0;
};
PlayerGraphics 类:
class PlayerGraphics :
public GraphicsComponent
{
public:
PlayerGraphics();
virtual ~PlayerGraphics();
virtual void Render(GameObject &gameObject);
virtual void Update(GameObject &gameObject, GameWorld &gameWorld, float gameTime);
};
PlayerGraphics 派生自 GraphicsComponent,而 GraphicsComponent 派生自 PrimaryComponent。
最佳答案
问题出在引用文献中:
行:
void GameObject::Attach_Component(std::unique_ptr<PrimaryComponent> &component)
应该是:
void GameObject::Attach_Component(std::unique_ptr<PrimaryComponent> component)
然后,当您调用它时,而不是:
player->Attach_Component(player_Graphics);
你应该这样做:
player->Attach_Component(std::move(player_Graphics));
也就是说,函数应该拥有指针的所有权。注意原来的player_Graphics
将被设置为 null(您将其移入,如果您想保留该对象的引用,那么您使用了错误的工具)。
您可能想知道为什么在您的代码中传递一个 std::unique_ptr<PrimaryComponent>
直接工作,但传递 std::unique_ptr<PlayerGraphics>
才不是。好吧,解释是您正在使用非常量引用,非常量引用只能绑定(bind)到完全相同时间的对象。然而,如果你按值传递参数,那么智能指针将被移动,一切都会正常工作。
这一切都是有道理的,std::unique_ptr
意味着不可复制、不可共享、可移动的智能指针。您应该四处移动指针,而不是通过引用传递它。
长话短说:如果 B
是 A
的子类你可以移动std::unique_ptr<B>
进入std::unique_ptr<A>
但你不能绑定(bind) std::unique_ptr<B>
到 std::unique_ptr<a>&
类型的引用.
附言。 move&cast 的构造函数声明如下:
template <class T, class D = default_delete<T>>
class unique_ptr
{
template <class U, class E>
unique_ptr (unique_ptr<U,E>&& x) noexcept;
};
关于C++ 错误 : A reference of type cannot be initialized with a value of type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33792850/