将对象的指针复制到此对象的新指针中

Copy Pointers of Object into New Pointer of this Object

本文关键字:指针 对象 复制 新指针      更新时间:2023-10-16

我有一个gameObject,它具有 std::vector<Component*> mComponents,我已经超载了 GameObject(const GameObject&)。我试图将mcomponent从一个复制到另一个,但是将每个包含的 Component*的s都完全放入 new对象中,但是使对象内容完全相同。这就是我目前拥有的:

gameObject.cpp

GameObject::GameObject(const GameObject& other) 
{
    if (this != &other)
    {
        this->mComponents = other.mComponents; // EDIT 1
        for (int i = 0; i < (int)mComponents.size(); i++)
        {
            // FILL this->mComponents with NEW objects but
            // containing the exact same data and 
            // variables from other.mComponents
            this->mComponents[i] = other.Copy(); // EDIT 2 EXAMPLE OF IDEA IN COMMENTS
            this->mComponents[i]->setParent(this);
        }
    }
}

Engine.cpp(提取(

GameObject cube, cube2;
cube.addComponent(new DirectionalLight(glm::vec3(-0.2f, -1.0f, -0.3f)));
cube.addComponent(new Texture("Resources/Textures/container.png", "Resources/Textures/container_specular.png"));
cube.addComponent(new Shader("Resources/Shaders/cube.shader"));
cube.addComponent(new Cube());
cube2 = GameObject(cube);

当我实例化cube2时,mcomponents Components*内容均完全相同,但我想创建一个新的 Component* s来从 GameObject(const GameObject&) fucntion中填充此 std::vector,同时使所有变量保持不变。

P.S。我知道大多数其他运营商(例如'='(不会为向量内部创建新组件,但是我将在我弄清楚如何用新的 Component*'s。

填充向量之后实现这一点。

this->mComponents[i]->Copy(other);无法正常工作。至少不是从纯粹的继承的角度来看。Supertype(基本(类型指针不能隐式施放到派生类型上。这称为降落,没有任何语言支持它。

这样做的一种更简单的方法是在每个组件中定义一个虚拟的"克隆"函数:

virtual Component* clone()=0; // base declaration
virtual Component* Texture::clone() //derived implementation
{
    return new Texture(*this);
} 

然后在您的游戏对象复制构造函数中:

    for (int i = 0; i < (int)other.mComponents.size(); i++)
    {
        // FILL this->mComponents with NEW objects but
        // containing the exact same data and 
        // variables from other.mComponents
        this->mComponents.push_back(other.mComponents->clone());
        this->mComponents[i]->setParent(this);
    }

这样,您让组件本身处理复制过程。