簡體   English   中英

復制和交換習語,帶繼承

[英]copy-and-swap idiom, with inheritance

我讀了有關復制和交換習語的有趣信息。 我的問題是關於從另一個類繼承時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 ???
    }
    .../...
};

你會交換子對象:

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

如果std::swap不能完成這項工作,你可能需要為Bar實現交換功能。 另請注意, swap應該是非成員(如有必要,還可以是朋友)。

只需將其轉換為基礎並讓編譯器解決它:

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

你通常會這樣做:

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);
    }
    .../...
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM