使用 2 参数复制构造函数

Copy constructor with 2 argument

本文关键字:构造函数 复制 参数 使用      更新时间:2023-10-16
    class Sample
    {
       public:
       Sample(){}
       Sample(const Sample& obj){ cout<<"C.C. with 1 argument called"<<endl;}
       Sample(const Sample& obj, int i){ cout<<"C.C. with 2 arguments called"<<endl;}
    };
    void main()
    {
         Sample s1;
         Sample s2 = s1; // Here, C.C with 1 arg. called.
    }

有几个问题:

  1. 如何调用具有 2 个参数的复制构造函数?
  2. 当我们
  3. 需要一个带有 1 个参数的复制构造函数时,当我们需要带有 2 个参数的 C.C 时?
具有

2 个(或更多(必需参数的构造函数不是复制构造函数。

1.:

Sample s2(s1, 0);

只是在这里添加一点形式主义。标准对"复制构造函数"术语(12.8(有严格的定义:
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 (8.3.6). [ Example: X::X(const X&) and X::X(X&,int=1) are copy constructors.

一个类实际上只有一个副本 ctor,它只能用一个参数调用。它可以接受两个(或更多(参数,但前提是它为其他参数提供默认值。无论哪种方式,第一个参数都必须是对相同类型对象的(通常是 const(引用。

你的第二个 ctor 采用两个参数并不是真正的复制 ctor(至少在通常使用该术语时(——它只是一个恰好将实例作为参数的 ctor(可能将新实例基于该参数,至少部分(。