向默认复制构造函数添加功能

Adding functionality to a default copy constructor

我有一个问题。假设我有一个 class A,我对默认的复制构造函数非常满意。

我可以向这个默认的复制构造函数添加功能而无需再次重写它的所有工作吗?

简单的例子:

class A 
{
public:
A(int n) : data(n) { };
private:
int data;
};

假设我想在每次调用复制构造函数时打印消息 "Copy constructor!"。对于这个简单的案例,我只需要编写自己的复制构造函数,它明确负责浅拷贝,并打印出消息。有没有办法在默认复制构造函数的顶部 添加消息打印(或我想要的任何其他功能),而无需明确编写浅层复制?

Suppose I want to print the message "Copy constructor!" each time a copy constructor is called. For this simple case I would just write my own copy constructor, which takes charge of the shallow copy explicitly, and also prints out the message.

是的,您需要明确提供复制构造函数并添加打印消息。

class A 
{
    public:
    A(int n) : data(n) { };
    // You need to add tis:
    A(const& A rhs) : data(rhs.data)  {
        std::cout << "Copy constructor!" << '\n';
    }
    private:
    int data;
};

Is there a way to add the message printing (or whatever other functionality I want) on top of the default copy constructor, without writing explictly the shallow coyp?

没有,没有。