簡體   English   中英

C ++如何設置類型為std :: vector的指針 <Derived*> 到類型為std :: vector的對象 <Base*>

[英]C++ How to set a pointer of type std::vector<Derived*> to object of type std::vector<Base*>

的背景:

我正在用C ++構建一個物理引擎,該引擎計算笛卡爾空間中n體系統的重力演化,然后將其轉換為任何預定義的坐標系集。 最終目標是使起始坐標系任意(在坐標系“ n”而不是僅笛卡爾坐標系中進行計算),但這是一個遙遠的目標。

問題:

因為該坐標系應該是可互換的,所以我使笛卡爾坐標系擴展了基本坐標系:

class CoordMember {
}

class CoordState {
   public:
      /* methods to operate on members */

   protected:
      std::vector<CoordMember*> members;
}

class Particle : public CoordMember {
}

class CartState : public CoordState {
}

嘗試創建類型為std::vector<Particle*>的指針時,該錯誤指向類型為std::vector<CoordMember*>的成員對象:

CartState* state = new CartState(/* initialization vars */);
std::vector<Particle*>* parts = static_cast< std::vector<Particle*>* >(&state->members);

編譯器錯誤是:

error: static_cast from 'std::vector<CoordMember *> *' to 'std::vector<Particle *> *' is not allowed
error: no viable overloaded '='

就這一點而言,我知道一個事實,即state->members中的數據都屬於Particle*類型。 我不知道要做什么才能使這種轉換成為可能。 有任何想法嗎?

tl; dr:

std::vector<Derived*>* ptr = static_cast< std::vector<Base*>* >(&object);
static_cast from 'std::vector<Derived*>*' to 'std::vector<Base*>*' is not allowed

強制轉換不起作用,因為vector 完全不相關 您必須將向量中的每個對象都強制轉換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM