2016-08-02 100 views
2

我想使用拷貝賦值操作符的默認功能,但能夠執行一些額外的任務作爲操作的一部分。因此,基本形式是這樣的:C++調用默認拷貝賦值操作符來自過載拷貝賦值操作符

class Test 
{ 
    void operator=(Test& that) 
    { 
     *this = that; //do the default copy operation 
     this->foo() //perform some other tasks 
    } 
}; 

這很容易通過創建一個副本()函數來完成,但它會很美好,維護「=」操作的清潔度。

回答

3

你可以從子類

// Fill this class with your implementation. 
class ClsImpl { 
    // some complicated class 
protected: 
    ~ClsImpl() = default; 
}; 

class Cls : public ClsImpl { 
public: 
    Cls& operator=(const Cls& other) { 
    if (this == &other) { return *this; } 
    // assign using the base class's operator= 
    ClsImpl::operator=(other); // default operator= in ClsImpl 
    this->foo(); // perform some other task 
    return *this; 
    } 
}; 
+2

爲什麼你使用'static_cast'強制調用基類的實現,而不是僅僅通過'ClsImpl ::運算符=(其他)顯式調用它;'。如果'ClsImpl'只是一種委託複製分配功能的方法,那麼您應該使用私有繼承來防止隱式轉換並引入切片風險。 –

+1

@CaptainObviously他們相同的事情,但省略演員是一種收益,我同意。如果私有繼承不需要大量的'using'聲明來公開所有基類的成員函數,那麼私有繼承將會非常好。 –

+0

是的,很多'using'語句會吸引人。無論如何,使基類中的複製構造函數和複製賦值運算符都受到保護。 –

0

的一種方法是從派生類派生再次提供複製後的邏輯使用基本實現類和委託到基地operator=

#include <iostream> 


// a wrapper class to provide custom copy actions 

template<class Base> 
struct CopyActions : Base 
{ 
    using base_class = Base; 
    using CopyActions::base_class::base_class; 

    // copy operator will call the base and then perform custom action 

    CopyActions& operator=(const CopyActions& r) { 
     base_class::operator=(r); 
     onCustomCopy(r, *this); 
     return *this; 
    } 
}; 

// a class to notify us when a copy takes place, without having to write 
// custom copy operators 
struct copy_sentinel 
{ 
    copy_sentinel operator=(const copy_sentinel&) { 
     std::cout << "copying " << name << '\n'; 
     return *this; 
    } 
    const char* name; 
}; 


int test_count = 0; 

// a model base class 
struct MyBase 
{ 
    int base_count = test_count++; 
    copy_sentinel base_s { "MyBase" }; 
}; 

// a model derived class containing only logic 
struct MyDerived : MyBase 
{ 
    int derived_count = test_count++; 
    copy_sentinel base_s { "MyDerived" }; 
}; 

// a custom copy action (free function) 
void onCustomCopy(const MyDerived& from, MyDerived& to) 
{ 
    std::cout << "custom copy action\n"; 
} 

// our derived class with custom copy actions 
using SuperDerived = CopyActions<MyDerived>; 

// test 
int main() 
{ 
    SuperDerived a; // 0, 1 
    SuperDerived b; // 2, 3 

    // prove initial values 
    std::cout << a.base_count << ", " << a.derived_count << std::endl; 

    // perform copy and report actions 
    a = b; 

    // prove a copy occurred 
    std::cout << a.base_count << ", " << a.derived_count << std::endl; 
} 

預計業績:

0, 1 
copying MyBase 
copying MyDerived 
custom copy action 
2, 3