使用 2 参数复制构造函数
Copy constructor with 2 argument
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.
}
有几个问题:
- 如何调用具有 2 个参数的复制构造函数?
当我们- 需要一个带有 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(可能将新实例基于该参数,至少部分(。
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 当从函数参数中的临时值调用复制构造函数时
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 使用复制构造函数复制双精度数组
- C 无可行的构造函数复制类型的变量
- 没有可行的构造函数复制类型 'MyString' 的数组元素
- 编译时,复制构造函数/复制分配和正常功能调用优化之间是否存在任何区别
- 如何最小化调用列表构造函数(复制构造函数)的次数?
- C 11矢量构造函数复制与范围
- 我定义了一个非复制构造函数;复制构造函数还会被隐式定义吗
- 可以将构造函数复制为转换运算符
- 将基类指针的构造函数复制到子类
- C++树类:构造函数/复制/内存泄漏
- 如何制作这个在模板构造函数复制中使用类型定义的类型的模板
- 将构造函数复制为模板化的成员函数
- 绕过私有复制构造函数/复制赋值C++
- C++通过构造函数复制对象
- 复制构造函数 - 复制C++中的对象
- 将带unique_ptr的类的构造函数复制到作为成员的抽象类