C++ 使用指向具有指针c++;
我有一个向向量添加指针的循环C++ 使用指向具有指针c++;,c++,pointers,C++,Pointers,我有一个向向量添加指针的循环 vector<Material *> materials; 在我的循环中: while(input_read_from_the_file !=NULL){ int id=someval1; float x[2]={someval2,someval3}; float y[2]={someval4,someval5}; materials.push_back(new Material(id,x,y)); } 当我在for循环中读取材质向量时,我看到ID不
vector<Material *> materials;
在我的循环中:
while(input_read_from_the_file !=NULL){
int id=someval1;
float x[2]={someval2,someval3};
float y[2]={someval4,someval5};
materials.push_back(new Material(id,x,y));
}
当我在for循环中读取材质向量时,我看到ID不同,但所有元素的氛围和漫反射都相同。这可能是因为它在while循环中使用了相同的指针,但我找不到替代方法。这里最好的方法是什么?
谢谢我会尽量避免使用指针。 让我们从向量开始。为什么它需要是
vector
而不是vector
?
除非Material
是继承类,否则可以使用Material
对象的向量而不是指针。
这样,您就不需要具有vector
的类的析构函数来迭代和销毁它们中的每一个(通过使用shared\u ptr
,您也可以避免这种情况)
现在,正如评论中所提到的,问题是材质
为氛围
和漫反射
成员使用指针。也没有理由。
从技术上讲,在编写渲染器或材质系统时,您希望它是Vector3
或Vector4
,但我们还是使用float[2]
来代替
C++11(0x)具有很酷的移动语义,您可以使用它来避免创建临时对象(因为我们要将一个对象推入向量,而没有移动语义,所以在这样做时会创建一个临时对象)
因此,您的代码如下所示:
class Material {
int id;
float ambiance[2]; // you really ought to use Vector2 instead. pointers are evil.
float diffuse[2];
Material (const int _id, const float _amb[], const float _dif[]) : id(_id) {
ambiance[0] = _amb[0]; ambiance[1] = _amb[1]; // actual copy is made
diffuse[0] = _dif[0]; diffuse[1] = _dif[1];
}
}
-----
vector<Material> materials;
while(input_read_from_the_file !=NULL){
int id = someval1;
float x[2]= {someval2,someval3};
float y[2]= {someval4,someval5};
materials.emplace_back(Material(id,x,y)); // or even materials.emplace_back(id, x, y);
}
类材料{
int-id;
浮动环境[2];//你真的应该用Vector2来代替。指针是邪恶的。
浮动扩散[2];
材质(常量内部id、常量浮动amb[],常量浮动dif[]):id(\u id){
环境[0]=\u amb[0];环境[1]=\u amb[1];//实际复制完成
漫反射[0]=_-dif[0];漫反射[1]=_-dif[1];
}
}
-----
载体材料;
while(输入\u从\u文件读取!=NULL){
int id=someval1;
浮点x[2]={someval2,someval3};
浮点y[2]={someval4,someval5};
materials.emplace_back(Material(id,x,y));//甚至materials.emplace_back(id,x,y);
}
指针指向while循环的局部变量。这是未定义的行为。为什么不存储数组或向量而不是指针?我应该在类中使用数组而不是指针吗?而不是漂浮的氛围;浮动环境[3]@Emrah是这样的:有一个合理且已知的固定数量,如果不将它们存储为声明的数组,那就太疯狂了。如果是这样,就不需要动态存储它们。如果有这样的需要,请使用向量。非常感谢,它解决了我的问题。我不是疯子,但我是初学者:)
class Material {
int id;
float ambiance[2]; // you really ought to use Vector2 instead. pointers are evil.
float diffuse[2];
Material (const int _id, const float _amb[], const float _dif[]) : id(_id) {
ambiance[0] = _amb[0]; ambiance[1] = _amb[1]; // actual copy is made
diffuse[0] = _dif[0]; diffuse[1] = _dif[1];
}
}
-----
vector<Material> materials;
while(input_read_from_the_file !=NULL){
int id = someval1;
float x[2]= {someval2,someval3};
float y[2]= {someval4,someval5};
materials.emplace_back(Material(id,x,y)); // or even materials.emplace_back(id, x, y);
}