复制和交换习语,带继承

时间:2011-09-22 13:35:20

标签: c++ inheritance idioms

我读了interesting things关于复制和交换习语的内容。我的问题是关于从另一个类继承时swap方法的实现。

class Foo : public Bar
{
    int _m1;
    string _m2;
    .../...
public:
    void swap(Foo &a, Foo &b)
    {
         using std::swap;

         swap(a._m1, b._m1);
         swap(a._m2, b._m2);
         // what about the Bar private members ???
    }
    .../...
};

3 个答案:

答案 0 :(得分:10)

你会交换子对象:

swap(static_cast<Bar&>(a), static_cast<Bar&>(b));

如果Bar没有完成工作,您可能需要为std::swap实现交换功能。另请注意,swap应该是非会员(如有必要,还应该是朋友)。

答案 1 :(得分:2)

将它转换为基础并让编译器解决它:

swap(static_cast<Bar&>(a), static_cast<Bar&)(b));

答案 2 :(得分:0)

你通常会这样做:

class Foo : public Bar
{
    int _m1;
    string _m2;
    .../...
public:
    void swap(Foo &b)
    {
         using std::swap;

         swap(_m1, b._m1);
         swap(_m2, b._m2);
         Bar::swap(b);
    }
    .../...
};