无效初始化类型为'std :: vector <object *>&amp;'</object *>的非const引用

时间:2011-05-06 16:18:50

标签: c++ vector g++

只是从C ++开始,因为我想将我的光线跟踪器从Python翻译成C ++。

无论如何,我正在尝试使用g++编译我的光线跟踪器,我收到此错误:

In file included from engine.cpp:10:0:
objects.cpp: In function ‘Vector Trace(Ray&, std::vector<Object*>&, float, int)’:
objects.cpp:97:30: error: conversion from ‘Object*’ to non-scalar type ‘Object’ requested
objects.cpp:110:29: error: conversion from ‘Object*’ to non-scalar type ‘Object’ requested
engine.cpp: In function ‘int main(int, char**)’:
engine.cpp:36:55: error: invalid initialization of non-const reference of type ‘std::vector<Object*>&’ from an rvalue of type ‘std::vector<Object*>*’
objects.cpp:86:8: error: in passing argument 2 of ‘Vector Trace(Ray&, std::vector<Object*>&, float, int)’

我知道所有这些错误都围绕着我的objects变量,因为我不确定如何制作对象数组并在函数内正确使用它。

这是main()的一部分:

vector<Object*> objects;

Sphere sphere = Sphere();
sphere.pos = Vector(0, 0, 0);
sphere.radius = 1;
sphere.diffuse = Vector(1, 1, 1);

objects.push_back(&sphere);

Trace()的减速:

Vector Trace(Ray &ray, vector<Object*> &objects, float roulette, int n = 0) {

Sphere的声明如下:

class Sphere: public Object {
  public:

我不确定该怎么做,因为我已经尝试过调整vector<>事情的所有内容!

修改

这是第 97 行:

Object target = objects[i];

1 个答案:

答案 0 :(得分:3)

您没有包含有问题的行。

objects.cpp:97你做的是这样的事情:

Object x = objects[0];

这不起作用,因为objectsObject *

的向量

使用例如其中之一:

Object * x = objects[0]; // x points to the actual Object in your vector
Object x = *objects[0]; // x is a copy of the Object in your vector
Object & x = *objects[0]; // x is a reference to/alias of the actual Object in your vector

在第二个错误中,您尝试传递vector<Object*> *,其中vector<Object*>是预期的。不要通过&objects,而只是通过objects