我在休息了1年之后開始用C 編程,我在這里和那里遇到了困難(并不是說我在休息之前真的了解它)。
我目前的問題是,我不知道如何正確使用指標。
我有以下的std::vector:
std::vector<std::shared_ptr<IHittable>> world。
其中IHittable是Hittable物件的介面。
現在,在這個std::vector中,推送了IHittable的多個派生,如Sphere,Triangle等。
這些派生類中的每一個都有一個函式intersects(),像這樣:
Intersection Sphere::intersects(const Ray & ray)
{
auto x = ...
...
return {x, this};
}
Intersection看起來是這樣的:
class Intersection>
{
public:
Intersection(double t, IHittable * object)。
[[nodiscard]] double t() const。
[[nodiscard]] IHittable * object() const;
private:
double t_;
IHittable * object_ = nullptr;
};
我真的不知道如何正確寫這段代碼。
我需要從一個物件的成員函式intersects()中回傳一個this指標,這個物件本身是動態分配的,并且存盤在一個std::shared_ptr中。
是否有辦法處理這個問題?
另一個例子:
std::vector<std::shared_ptr<IHittable>> world。
world.push_back(std::make_shared<Sphere>()) 。
auto s = Intersection(4.0, world[0] )。)
應該可以。
PS: 我可以直接創建多個std::vector,而不需要std::shared_ptr:
std::vector<Sphere> spheres;
std::vector<Triangles> spheres;
...
但是,IMHO,如果能一次性迭代每個物件,那就更好了。
PS2:我現在正在使用shared_from_this(),我的大部分代碼都能作業,謝謝。
uj5u.com熱心網友回復:
我認為這聽起來很適合std::enable_shared_from_this,正如Remy在評論中指出的。
我做了一個簡化的例子,希望能讓大家明白如何使用它來實作你所追求的目標。
class Intersection。
class IHittable : public std::enable_shared_from_this< IHittable> {
public:
virtual Intersection intersects( )= 0。
virtual void print( ) const= 0;
virtual ~IHittable( ) = default;
};
class Intersection {
public:
Intersection( std::shared_ptr<IHittable> object )
: object_{ std::move( object ) }
{ }
void print_shape( ) const {
object_->print( )。
}
private:
std::shared_ptr<IHittable> object_;
};
class Square : public IHittable {
public:
Intersection intersects( ) override< /span>{
return Intersection{ shared_from_this( ) }。
}
void print( ) const override{
std::cout << "Square
"。
}
};
int main( ) {
std::vector<std::shared_ptr<IHittable>> objects{
std::make_shared<Square> ( ) }。
const auto intersect{ objects.front( )->intersects( ) };
intersect.print_shape( )。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/331847.html
標籤:
