类型为"std::vector<Object*>&"的非常量引用的初始化无效

invalid initialization of non-const reference of type ‘std::vector<Object*>&’

本文关键字:常量 非常 引用 初始化 无效 lt vector 类型 Object std gt      更新时间:2023-10-16

刚刚开始使用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];

您没有包括有问题的行。

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