可能重複:
Conversion between Derived** to Base**我不能從指針指向派生類的指針和指向基類的指針嗎?
我收到回C++經過幾年大多的Python,和我打起來反對強類型的牆。我認爲我有基本的多態性和基類派生類指針之間的類型轉換(例如Can a pointer of a derived class be type cast to the pointer of its base class?),但是這裏有一個stumper:爲什麼我不能指派一個指向派生類的指針指向p- to-p到它的基類?
欲瞭解更多的上下文(也許提示做這個更少pythonishly),這是我試圖做的簡化版本。我想要一個指向對象的指針列表(從單個類派生)和一個標識它們的字符串(即一個map<string, obj*>
)。然後一組組件將通過識別字符串和位置的列表來存儲指向相應對象的指針(即map<string, obj**>
)。然後,我應該能夠通過其字符串ID找到適當的對象,然後填寫適當的指針供組件隨後使用。 簡化代碼做,這是
#include <map>
#include <string>
using namespace std;
class base
{
};
class derived: public base
{
};
typedef map<string, base**> BasePtrDict;
typedef map<string, base*> BaseDict;
int main(int argc, char* argv[])
{
base b1, b2;
derived d;
derived* d_ptr;
BaseDict base_dict;
base_dict["b1"] = &b1;
base_dict.insert(make_pair("b2",&b2)); // alternate syntax
base_dict["d"]= &d;
BasePtrDict ptr_dict;
ptr_dict["d"] = &d_ptr;
for (auto b = ptr_dict.begin(); b != ptr_dict.end(); b++)
*(b->second) = base_dict[b->first];
return 0;
}
這在ptr_dict["d"] = &d_ptr;
運行到一個編譯錯誤。爲什麼?在C++範例中,我該怎麼做?我真的需要做到醜陋(不安全?)reinterpret_cast<base>()
無處不在嗎?
謝謝所有有用的參考和示例。現在肯定有意義,我不得不考慮如何在保持強大的打字ala C++的同時優雅地做到這一點。 – Bismark 2012-07-12 09:00:57