简体   繁体   English

连接声明和赋值时,是否不调用默认构造函数?

[英]Is the default constructor not called when declaration and assignment are joined?

I have created a class coor and overloaded a + operator 我创建了一个类库,并重载了+运算符

class coor
{
    coor(){std::cout<<"default constructor called\n";};
    coor operator +(coor param) const;
};

coor coor::operator+(coor param) const
{
    ....    
}


int main() {
    coor obj1;
    coor obj2;
    coor obj3 = obj1 + obj2;
    std::cin.get();
    return 0;
}

Why is the default constructor of obj3 is not called? 为什么未调用obj3的默认构造函数? It is called when declarartion and assignment and seperated. 在声明和分配并分开时调用它。

With

coor obj3 = obj1 + obj2

you copy-construct obj3 from the result of obj1 + obj2 (which is a so-called r-value and a temporary object). 您可以从obj1 + obj2 (这是所谓的r值和一个临时对象)的结果中复制-构造 obj3

Even though = is used here, it's not assignment but initialization. 即使在这里使用= ,它也不是赋值,而是初始化。

"Why is the default constructor of obj3 is not called?" “为什么不调用obj3的默认构造函数?” - Because of the rules of copy initialization - which is what is happening here. -由于复制初始化的规则-这就是这里发生的情况。

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

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