我正在尝试为给定的骨架代码中的球体实现光线跟踪算法
要计算Delta
,我想使用获得半径和球体的中心。我得到一个类Scene
的对象作为导入:
void render(image2D<float4>& framebuffer, const Scene& scene, float w_s, float
f, const float4& background_color)
类Scene
看起来像这样:
class Scene
{
Scene(const Scene&) = default;
Scene& operator =(const Scene&) = default;
std::vector<Sphere> spheres;
public:
Scene() = default;
void addSphere(const float3& c, float r);
};
所以类Scene
包括<Sphere>
的向量,其中Sphere
看起来像这样:
struct Sphere
{
float3 c;
float r;
};
所以我试图从导入Sphere
这样得到中心和半径
std::cout << "Sphere radius: " << scene.spheres.(0).r << std::endl;
但我得到scene.spheres
是私人的。我们不允许更改.h
文件。我怎么能处理这个为c
和r
获取球体的每个对象的值?
如果您可以访问spheres
,您可以写:
std::cout << "Sphere radius: " << scene.spheres[0].r << std::endl;
或更好:
for (auto& x: scene.spheres)
std::cout << "Sphere radius: " << x.r << std::endl;
但是由于spheres
是Scene
的私有,除非你可以更改Scene
的定义,并且要么在spheres
上提供迭代器,要么为spheres
提供getter,或者让你的渲染函数成为类的朋友,否则你无法访问它。
你不能。
该类使您无法访问其内容,如果您无法更改它,那么您没有解决方案。
这是一个设计很差的课程。
有一个简单但不可否认的hacky方式来解决你的问题。我不能同意其中一条评论说这是一个糟糕的设计。但是如果你不允许触摸头文件,那么改变Scene
类的设计,那么这就是你可以做的。
您的光线跟踪器不需要按照说法访问具体对象。它所需要的只是它们的属性值。但是当向量是私有的时候你无法得到它。这是事实。但是没有什么可以阻止你创建一个重复的向量并使用它将值传递给Scene向量并使用该重复的向量来访问属性数据。
#include <iostream>
#include <vector>
struct Sphere // can't touch this!
{
float c;
float r;
Sphere(float c_, float r_) : c(c_), r(r_)
{;}
};
class Scene // can't touch this!
{
private:
Scene(const Scene&) = default;
Scene& operator = (const Scene&) = default;
std::vector<Sphere> spheres;
public:
Scene() = default;
void addSphere(float c, float r)
{
spheres.emplace_back(c,r);
}
};
int main()
{
Scene scene;
std::vector<Sphere> spheres_duplicate = {{1.0,2.0},{3.0,4.0},{2.0,6.0}}; // duplicated vector.
for (auto &&i : spheres_duplicate)
scene.addSphere(i.c, i.r); // fill in the scene vector, so now you have 2 vectors.
std::cout << "Sphere radius: " << spheres_duplicate[0].r << std::endl; // access attributes from duplicated vector.
}
它有效,但这个解决方案的问题是你需要维护2个向量。不只是一个。