我需要在C++中存儲對派生類實例的引用。我考慮使用shared_ptrs向量到基類(因爲它需要持有不同類型的派生類),但是,重要的是容器包含原始指針,而vector(或其他stl容器)則不是這種情況,如果我沒錯的話。有沒有一種方法可以在本地C++中執行此操作,還是必須使用像Boost的ptr_vector這樣的特殊容器?C++:原始指針的容器
編輯:這是我的測試代碼:
class Foo
{
public:
Foo() {}
virtual ~Foo() {}
virtual void set_x(int i) = 0;
};
class Bar : public Foo
{
public:
Bar() {}
void set_x(int i)
{
this->x = i;
}
int x;
};
int main()
{
Bar bar;
// ptr
std::cout << &bar << "\n";
std::vector<Foo*> foos;
foos.push_back(&bar);
// different ptr value
std::cout << &foos[0] << "\n";
foos[0]->set_x(1);
// however, changes are made
std::cout << bar.x;
return 0;
}
由於提前,
耶拿
會向量(指向您的對象的指針矢量)不適合你嗎? –
JoshD
2010-09-27 03:10:43
我不清楚爲什麼一個'shared_ptr'容器不適合你。 – 2010-09-27 03:13:25
我嘗試過,但是當我通過vector.push_back(&instance)添加實例的指針時,向量中的指針與原始指針不同。 – jena 2010-09-27 03:14:13