2016-08-02 63 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 
相关问题