如何覆盖c ++类像vector [英] How to override c++ class like vector
问题描述
我想覆盖向量类并添加一个自定义函数,但来自Java我不太熟悉重写,继承和那种东西的机制。
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.
推荐答案
标准容器不是多态的,因此你不能覆盖它们的行为;并没有受保护的成员,所以没有继承他们来延伸他们的点。
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.
虽然你可以这样做,如另一个答案所建议的,你必须重新实现所有的构造函数(或者,自2011年以来,明确继承它们) t继承;并且有一种危险,有人对它进行多态处理,例如,当类不支持基类时,通过指向基类的删除。
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++);
}
这篇关于如何覆盖c ++类像vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!