【发布时间】:2012-12-12 09:42:37
【问题描述】:
我有一个名为Path 的类扩展std::vector<Square *>,其中Square 也是我创建的一个类。 Path 将作为实体穿越 2D 环境的指南。我需要获得最长路径和最短路径,因此我希望在Path 中找到两个Squares 之间的平方数。为此,我觉得重载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; };
};
当然,我想我可以只为超类编写一个调用 push_back 的方法,但我觉得重写该函数更简洁,而且学习如何正确重写 stl 对我来说是一个好习惯功能。
谢谢!
【问题讨论】:
-
Nooooooooooooooooooo,你继承自 std::vector。用火杀死它!!1
-
保留带有双下划线的标识符。你不应该使用它们。标准库使用它们是因为它们是为标准库保留的。
-
谢谢大家!我想我从来没有想过从 STL 继承可能是不好的做法。
标签: c++ inheritance vector overriding overloading