在指向对象的指针向量中取消引用
我正在尝试访问向量容器中保存的指针所指向的对象(称为向量),但我似乎无法访问它。
以下是重要的代码片段:
int main{
Vector<double>* test = new Vector<double>(randvec<double>());
test->save();
cout << Element::vectors[0];
return 0;
}
其中 Vector
是模板类,randvec
返回对向量的引用,save()
是
template <class T>
void Vector<T>::save()
{
vectors.push_back(this);
}
并且向量是static std::vector
在 Element.h 中定义,Vectors 的基类。
我这一切都错了吗?我试图通过使用指向主类的指针向量将派生类的所有元素包含在基类的静态数据成员中。
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)'
为什么我不能取消引用该指针?
I'm trying to access the object (called a Vector) pointed to by a pointer held in a vector container, but I can't seem to get to it.
Here are the important code snippets:
int main{
Vector<double>* test = new Vector<double>(randvec<double>());
test->save();
cout << Element::vectors[0];
return 0;
}
Where Vector
is a template class, randvec<T>()
returns a reference to a vector, save()
is
template <class T>
void Vector<T>::save()
{
vectors.push_back(this);
}
and vectors is static std::vector<Element*> vectors;
defined in Element.h, the base class of Vectors.
Am I going about this all wrong? I'm trying to contain all the elements of a derived class in a static data member of the base class by using a vector of pointers to the main class.
My output from main() might tell you what's going on – I get the pointer 0x1001000a0
. However, if I try to dereference that pointer, I get the following error:
error: no match for 'operator<<' in 'std::cout << * Element::vectors.
std::vector<_Tp, _Alloc>::operator[] [with _Tp = Element*, _Alloc = std::allocator<Element*>](0ul)'
Why can't I dereference this pointer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题不在于解除引用。问题是“<<”没有为 Element::vectors 定义运算符
The problem is not with dereferencing. The problem is that "<<" operator is not defined for Element::vectors
您似乎缺少可用于输出
Element
的operator<<
重载。请注意,如果您只定义Vector
的重载,它将不起作用,因为取消引用Element::vectors[0]
会为您提供一个类型的对象元素
。(未经测试,抱歉)示例,说明如何允许派生类(例如
Vector
)覆盖Element
的流插入行为:这是一个
Element
的虚拟成员函数:为
Element
重载operator<<
来调用该函数:然后重写派生类中的虚拟成员函数控制它们的书写方式:
It looks like you're missing an
operator<<
overload that can be used to output anElement
. Note that it won't work if you just define the overload forVector<T>
because dereferencingElement::vectors[0]
gives you an object of typeElement
.Here's an (untested, sorry) example of how you can go about allowing derived classes (like
Vector<T>
) to override the stream-insertion behaviour ofElement
:Add a virtual member function to
Element
:Overload
operator<<
forElement
to call this function:Then override the virtual member function in the derived classes to control how they should be written: