当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Is this considered as a copy constructor?

问题描述:

I know that a copy constructor is a constructor that makes a new object as a copy of an existing object, but, is every constructor that takes another object as an argument called a copy constructor?

Example: If I have to classes X and Y is X(const Y& y) a copy constructor?

If not is there a name for such constructor?

网友答案:

No this

X(const Y& y);

is not a copy constructor. The copy constructor shall define the first parameter having the same type (with/without qualifiers) as the created object

According to the C++ Standard

2 A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments

Constructor

X(const Y& y);

is a conversion constructor that converts an object of type Y to an object of type X.

网友答案:

No. A copy constructor is one which takes a single instance of the same class as it a ctor for. Hence

 X(const X& x)

is a copy constructor, as would be:

 X(const X& x, int z = 0)

since it can be called with just the single x object.

Constructors which take some other object are often called "converting constructors", but that name is as fixed as "copy constructor".

网友答案:

If X and Y are different types, then

X(const Y& y)

would be a conversion constructor.

Note that copy constructor is considered a special case of conversion constructor (for X==Y).

分享给朋友:
您可能感兴趣的文章:
随机阅读: