重构从std :: container继承的类 [英] Refactoring a class which inherited from a std::container

查看:75
本文介绍了重构从std :: container继承的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个中等的代码块,其中包含5个类,它们都是从标准容器中继承的.例如:

I've a medium chunk of code containing 5 classes that they're all inherited from standard containers. For example:

class Step : public std::vector<unsigned int>
{
public:
    friend std::ostream& operator<<(std::ostream& outStream, const Step& step);
    Step& operator =(const Step& rhv);
    static Step fromString(const std::string &input);
    std::string name;
};

我知道从标准容器中继承是一个坏主意,因此我将通过添加父数据类型的子对象来删除所有继承:

I know it's a bad idea to inherit from standard containers, so I'm going to remove all inheritances by adding a subobject of parent datatype:

class Step
{
public:
    friend std::ostream& operator<<(std::ostream& outStream, const Step& step);
    Step& operator =(const Step& rhv);
    static Step fromString(const std::string &input);
    std::string name;
    // std::vector interface:
    inline std::vector<unsigned int>::const_iterator begin() const {return data.begin();}
    inline std::vector<unsigned int>::const_iterator end() const {return data.end();}
    inline size_t size() const {return data.size();}
    typedef std::vector<unsigned int>::const_iterator const_iterator;
private:
    std::vector<unsigned int> data;
};

之所以这样做,是因为该代码已在其他程序中广泛使用,并且更改结构的成本非常高.

I'm doing this because the code is widely used in other programs and changing structure is very costly.

还有一个问题:您建议通过小改动来修改代码吗? (尽可能少)

And question: what do you suggest to revise the code by small changes? (as less as possible)

说明: 我有一些继承自stl容器的类.并且有很多使用它们的代码.我的问题是,如何在不使用这些类更改代码的情况下删除该邪恶继承?

Clarification: I have a some classes inherited from stl containers. And there are lots of codes using them. My question is that how do I remove that evil inheritance without changing codes using those classes?

推荐答案

一个可能的解决方案:将继承设为私有(或在可行的情况下受保护),并using相关成员:

One potential solution: making the inheritance private (or protected, if it makes sense), and using the relevant members:

class Step : private std::vector<int>
{
    typedef std::vector<int> base_;

public:
    using base_::operator[];
    using base_::size;
    ...

};

如果继承确实使代码更简单,那么您可能会喜欢这种解决方案.从容器继承的真正问题是,一旦将成员添加到Step类中,向vector的转换可能会给您带来麻烦:析构函数发生变化,并且您知道,它最初不是虚拟的.私有继承解决了这个问题.

If inheritance indeed made the code simpler, then you may like this solution. The real problem with inheriting from containers is that the conversion to vector may get you in trouble once you add members to the Step class: the destructor changes, and you know, it's not virtual in the first place. Private inheritance solves this problem.

这篇关于重构从std :: container继承的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆