是的,包装比继承更好,但前提是您需要向现有数据结构添加状态。否则,添加非成员函数。这在 C++ 编码标准 ( Amazon )的第 35 项中有更详细的解释
要添加状态,更喜欢组合而不是继承。诚然,必须为要保留的成员函数编写传递函数很乏味,但这样的实现比使用公共或非公共继承要好得多,也更安全。
template<typename T>
class MyExtendedVector
{
public:
// pass-through functions for std::vector members
void some_existing_fun() { return vec_.some_existing_fun(); }
// new functionality that uses extra state
void some_new_fun() { // your implementation here }
private:
std::vector<T> vec_;
// extra state e.g. to do logging, caching, or whatever
};
要添加行为,最好添加非成员函数而不是成员函数。
但是,请确保您的算法尽可能通用:
// if you CAN: write algorithm that uses iterators only
// (and delegates to iterator category that container supports)
template<typename Iterator, typename T>
bool generic_contains(Iterator first, Iterator last, T const& elem)
{
// implement using iterators + STL algorithms only
return std::find(first, last, elem) != last;
}
// if you MUST: write algorithm that uses specific interface of container
template<typename T>
void vector_contains(std::vector<T> const& v, T const& elem)
{
// implement using public interface of Container + STL algorithms
return generic_contains(v.begin(), v.end(), elem);
}