C ++从重载的复制赋值运算符调用默认的复制赋值运算符

时间:2016-08-02 23:27:04

标签: c++

我想使用复制赋值运算符的默认功能,但能够在操作过程中执行一些其他任务。所以基础形式看起来像这样:

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

这可以通过创建一个copy()函数轻松完成,但保留" ="的清洁度会很好。操作

2 个答案:

答案 0 :(得分:3)

您可以使用基本实现类并从子类

委托基础operator=
// 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;
  }
};

答案 1 :(得分:0)

一种方法是从派生类中再次派生以提供复制后逻辑。

#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