How to override c++ class like vector

丶灬走出姿态 提交于 2020-01-06 13:55:21

问题


I'm trying to override the vector class and add a custom function to it, but coming from Java I'm not really familiar with the mechanics of overriding, inheriting and that kind of stuff.


回答1:


The standard containers aren't polymorphic, so you can't override their behaviour; and have no protected members so there's no point inheriting from them to extend them.

While you could do that, as suggested by another answer, you would have to reimplement all the constructors (or, since 2011, explicitly inherit them), since those aren't inherited; and there's a danger of someone treating it polymorphically, for example deleting via a pointer to the base class, when the class doesn't support that.

Instead, add functionality through non-member functions operating on the public interface:

template <typename T>
void frobnicate(std::vector<T> & v) {for (auto & x : v) frobnicate(x);}

More generically, follow the example of the standard library and write a template operating over a general iterator range:

template <typename InputIterator>
void frobnicate(InputIterator begin, InputIterator end) {
    while (begin != end) frobnicate(*begin++);
}


来源:https://stackoverflow.com/questions/19463972/how-to-override-c-class-like-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!