c++ - 重写 push_back C++

标签 c++ inheritance vector overriding overloading

我有一个类叫做 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/

相关文章:

删除时出现 C++ 内存错误 - 调试断言失败

html - 行高继承

ios - 从初始化程序返回之前,不会在所有路径上调用“super.init”

c++ - SDL 事件队列

c++ - 简单数组查找最高值和最低值的索引位置

Objective-C 库多重继承

python - 将网格放置在一组无序点上的算法

matlab - 在定义的圆锥区域内创建随机单位向量

c++11 - 如何有效地将元素从集合移动到向量?

c++ - arduino count++ 有限制吗?如何解决?