这些对象初始化有什么区别? [重复]

时间:2021-11-04 13:20:14

This question already has an answer here:

这个问题在这里已有答案:

There are two type of object initialisation using copy constructor:

使用复制构造函数有两种类型的对象初始化:

Class object2(val1, val2); // <--- (1)

Same can be done by copying the contents of another class:

同样可以通过复制另一个类的内容来完成:

Class object1(val1, val2);
Class object2 = object1;  // <--- (2)

What is the difference between (1) and (2) ? Are they explicit calls and implicit calls or does it have to do with operator overloading?

(1)和(2)之间有什么区别?它们是显式调用和隐式调用还是与运算符重载有关?

2 个解决方案

#1


2  

Both constructs use constructors, but different constructors. First is a constructor taking two arguments, second is normally the copy constructor (can be defaulted). The explicit declarations should be like:

两个构造都使用构造函数,但使用不同的构造函数。首先是一个带有两个参数的构造函数,第二个通常是复制构造函数(可以是默认的)。显式声明应该是:

class Class {
    // constructor taking 2 args
    Class(int val1, const std::string& val2);
    // copy ctor
    Class(const Class& other);

    /* you could optionaly have a move ctor:
    Class(Class&& other); */
    ...
};

#2


1  

Here

这里

1. case 1

Class object2(val1, val2);

will call the constructor with two arguments

将使用两个参数调用构造函数

Class(type a, type b);

2. case 2

Class object2 = object1;

will call the copy constructor

将调用复制构造函数

Class(const Class&);

Demo

演示

#1


2  

Both constructs use constructors, but different constructors. First is a constructor taking two arguments, second is normally the copy constructor (can be defaulted). The explicit declarations should be like:

两个构造都使用构造函数,但使用不同的构造函数。首先是一个带有两个参数的构造函数,第二个通常是复制构造函数(可以是默认的)。显式声明应该是:

class Class {
    // constructor taking 2 args
    Class(int val1, const std::string& val2);
    // copy ctor
    Class(const Class& other);

    /* you could optionaly have a move ctor:
    Class(Class&& other); */
    ...
};

#2


1  

Here

这里

1. case 1

Class object2(val1, val2);

will call the constructor with two arguments

将使用两个参数调用构造函数

Class(type a, type b);

2. case 2

Class object2 = object1;

will call the copy constructor

将调用复制构造函数

Class(const Class&);

Demo

演示