类型为"std::vector<Object*>&"的非常量引用的初始化无效
invalid initialization of non-const reference of type ‘std::vector<Object*>&’
我刚刚开始使用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];
这是行不通的,因为objects
是Object *
的载体
例如,使用其中之一:
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
相关文章:
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 通过多个头文件使用常量变量
- 在cuda线程之间共享大量常量数据
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 是默认情况下分配给char数组常量的值
- 私有类型的静态常量成员
- OpenGL大的3D纹理(>2GB)非常慢
- 类似枚举的计算常量
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 使用常量键但非常量值进行映射
- 为什么`is_open()`非常常量
- 从getter方法返回常量和非常量值
- 阻止const类函数在引用成员上调用非常常量类函数
- C++初始化非常大的常量数组,最佳实践
- 提高c++中非常大的常量的可读性