首页 > c++ > 是否可以在Derived类中使用复制构造函数而不使用Base复制构造函数?

是否可以在Derived类中使用复制构造函数而不使用Base复制构造函数? (Is it possible to use a copy constructor in Derived class without using Base copy constructor?)

问题

我是C ++的新手,从我学到的东西到现在为止,当我们从Derived类调用复制构造函数时,会调用Base类的复制构造函数。假设我在Base类的私有区域中有一个复制构造函数。如何在不调用Base类的复制构造函数的情况下调用Derived类的复制构造函数?(在这段代码中,A没有复制构造函数的实现,这就是我想知道的)。

class NonCopyable
{
protected:
NonCopyable(){}
~NonCopyable(){}
private:
NonCopyable(const NonCopyable& nonCopyable);
NonCopyable& operator=(const NonCopyable& nonCopyable);
};
class A: public NonCopyable
{
};

解决方法

简单的答案是:是的,这是可能的。

您只需要定义一个调用NonCopyable复制构造函数的专用Derived复制构造函数(当然这可能只是在真正的软件应用程序中混淆,但这是一个不同的问题):

这个类是可构造的,但不是可复制构造的:

class CannotBeCopied: public NonCopyable {};

这个类是可构造的,也是可复制构造的:

class CanBeCopied: public NonCopyable {
public: 
    CanBeCopied() = default; // needed since otherwise CopyConstructor is only known construtor
    CanBeCopied(const CanBeCopied& b) { } // calls NonCopyable::NonCopyable() default-constructor, which is just protected
};

请参阅此处的生活示例:http//coliru.stacked-crooked.com/a/60c9fc42fa2dd59a

问题

I am new to C++ and from what i learned until now is when we call a copy constructor from a Derived class, The copy constructor of the Base class is called. Let's say that i have a copy constructor in the private area of the Base class. How can i call the copy constructor of the Derived class without calling the copy constructor of the Base class? (In this code A doesn't have the implementation of the copy constructor and this is what i would like to know).

class NonCopyable
{
protected:
NonCopyable(){}
~NonCopyable(){}
private:
NonCopyable(const NonCopyable& nonCopyable);
NonCopyable& operator=(const NonCopyable& nonCopyable);
};
class A: public NonCopyable
{
};

解决方法

The simple answer is: yes, this is possible.

You only need to define a dedicated Derived copy-constructor that does not call the NonCopyable copy-constructor (of course this might be just confusing in a real software application, but this is a different issue):

This class is constructible, but not copy-constructible:

class CannotBeCopied: public NonCopyable {};

This class is constructible, and also copy-constructible:

class CanBeCopied: public NonCopyable {
public: 
    CanBeCopied() = default; // needed since otherwise CopyConstructor is only known construtor
    CanBeCopied(const CanBeCopied& b) { } // calls NonCopyable::NonCopyable() default-constructor, which is just protected
};

See life example here: http://coliru.stacked-crooked.com/a/60c9fc42fa2dd59a

相似信息