将对象的指针复制到此对象的新指针中
Copy Pointers of Object into New Pointer of this Object
我有一个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);
}
这样,您让组件本身处理复制过程。
相关文章:
- 为什么指针对象没有调用默认构造函数
- 如何访问双指针对象中的方法
- 如何使用智能指针对象执行成员函数指针
- 调用带有指针对象错误的指针变量
- 如何从模板类重载创建的指针对象上的运算符?
- C++指针对象的运算符重载
- 如何初始化数组指针对象
- 如何打印出唯一指针对象向量中的值(基于范围的循环)?C++
- C++指针对象差异
- 涉及继承,指针对象的交易以及何时进行的问题
- 表达式必须在C 中具有指针对象类型
- 下标需要数组或指针类型表达式必须具有指针对象类型
- 字符指针对象和相应的字符数组元素比较
- 如何在 c++ 中克隆为弱指针对象
- 指针对象使用CPP中的指针表达式进行比较
- Visual Studio中智能指针对象的自定义视图
- 使用指针 /对象 /模板参数正确构成
- 如果我确定只有一个线程一次处理指针/对象,则C/C 仍应使用同步
- 如何将值分配给指针对象 c++
- 更改智能指针对象,然后访问它