简体   繁体   English

通过赋值初始化C ++对象时会发生什么?

[英]What happens when you initialize a C++ object by assignment?

From what I understand, assignment uses the operator= function, and initialization uses the contsructor. 据我了解,赋值使用operator=函数,初始化使用constructor。 But when you assign another object during declaration, what happens? 但是,当您在声明期间分配另一个对象时,会发生什么? I would have thought that car2 would initialize with car1 's data, but I can't tell. 我本以为car2会使用car1的数据进行初始化,但我无法确定。 Does it initialize with the default constructor first, and then re-assign the data? 它是否首先使用默认构造函数进行初始化,然后重新分配数据? I tried writing a quick program and traced it with a debugger, but it wouldn't let me look through the important line Car car2 = car1 . 我尝试编写一个快速程序,并使用调试器对其进行了跟踪,但它不允许我浏览重要的行Car car2 = car1 I've included my program below. 我在下面包含了我的程序。

#include <iostream>
#include <string>

class Car
{
public:
    Car();
    Car(std::string color, std::string make);

private:
    std::string color;
    std::string make;
};

Car::Car() {
    this->color = "None";
    this->make = "None";
}

Car::Car(std::string color, std::string make) {
    this->color = color;
    this->make = make;
}

int main() {
    Car car1("blue", "Toyota");
    Car car2 = car1;
    return 0;
}

Car has an implicitly declared copy-ctor , which is used here as the ctor-call cannot be elided (it is not initialized with a pr-value), nor is move-construction possible (it is not an xvalue). Car有一个隐式声明的copy-ctor ,在这里使用它是因为ctor调用不能被忽略(它不使用pr值初始化),移动构造也不可能(它不是xvalue)。

That implicitly-declared copy-ctor does member-wise copy-construction. 隐式声明的copy-ctor进行成员明智的复制构造。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM