我有一个类叫做 Path
延伸 std::vector<Square *>
, 其中Square
也是我创建的一个类。 Path
将作为实体穿越 2D 环境的指南。我需要获得最长路径和最短路径,因此我希望找到两个 Squares
之间的方 block 数在Path
.为此,我觉得重载会有好处,std::vector<Square *>::push_back(const value_type &__x)
,虽然我不确定它的语法是什么。我目前正在尝试这个:
class Path : public std::vector<Square *>
{ //... functional stuff, not relevant.
int length;
public:
push_back(const value_type &__x)
{ Square *last_square = this->at(this->size() - 1);
// how do I call super class push_back?
// however that works, I push back &__x square here.
Square *most_recent = (Square *)&__x;
int delta_x = compare_distance(last_square, most_recent);
length += delta_x;
};
int path_length() { return length; };
};
当然,我想我可以只写一个方法,在其中为父类(super class)调用 push_back,但我觉得重写函数更简洁,而且学习如何正确重写 STL 对我来说是个好习惯功能。
谢谢!
最佳答案
plus it is good practice for me to learn how to properly override stl functions.
其实不是。
STL 容器不打算被继承(没有虚拟
方法),因此好的做法是使用组合并为使用 STL 的类提供有意义的接口(interface)实现其目标的容器方法。
关于c++ - 重写 push_back C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13836881/