问题
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