2

我正在尝试访问由向量容器中保存的指针指向的对象(称为向量),但我似乎无法访问它。

以下是重要的代码片段:

int main{
    Vector<double>* test = new Vector<double>(randvec<double>());

    test->save();

    cout << Element::vectors[0];
return 0;
}

Vector模板类在哪里,randvec<T>()返回对向量的引用,save()

template <class T>
void Vector<T>::save()
{
    vectors.push_back(this);
}

向量static std::vector<Element*> vectors;在 Vectors 的基类 Element.h 中定义。

我对这一切都错了吗?我试图通过使用指向主类的指针向量将派生类的所有元素包含在基类的静态数据成员中。

我的 main() 输出可能会告诉你发生了什么——我得到了指针0x1001000a0。但是,如果我尝试取消引用该指针,我会收到以下错误:

error: no match for 'operator<<' in 'std::cout << * Element::vectors. 
std::vector<_Tp, _Alloc>::operator[] [with _Tp = Element*, _Alloc = std::allocator<Element*>](0ul)'

为什么我不能取消引用这个指针?

4

2 回答 2

2

问题不在于取消引用。问题是没有为 Element::vectors 定义“<<”运算符

于 2010-06-22T04:30:27.277 回答
1

看起来您缺少operator<<可用于输出Element. 请注意,如果您仅定义重载 for 将不起作用,Vector<T>因为取消引用Element::vectors[0]会为您提供 type 的对象Element

这是一个(未经测试,抱歉)示例,说明如何允许派生类(如Vector<T>)覆盖 的流插入行为Element

将虚拟成员函数添加到Element

class Element
{
   // other stuff

   virtual void write_to_stream(std::ostream& stream) const = 0;
};

调用此函数operator<<的重载:Element

std::ostream& operator<<(std::ostream& stream, const Element& element)
{
    element.write_to_stream(stream);  // dynamic dispatch as we call through reference
    return stream;
}

然后重写派生类中的虚成员函数来控制它们应该如何编写:

template<class T>
class Vector : public Element
{
   // other stuff
   virtual void write_to_stream(std::ostream& stream) const
   {
      // whatever you like goes here
   }
};
于 2010-06-22T04:32:05.713 回答