简体   繁体   English

为什么使用复制构造函数而不是赋值运算符

[英]Why is the copy constructor being used instead of the assignment operator

This is how MyClass is defined: 这是MyClass的定义方式:

class MyClass {
    double x, y;
    public:
        MyClass (double a = 0., double b = 0.) {
            x = a;
            y = b;
            cout << "Using the default constructor" << endl;
        }
        MyClass (const MyClass& p) {
            x = p.x;
            y = p.y;
            cout << "Using the copy constructor" << endl;
        }
        MyClass operator =(const MyClass& p) {
            x = p.x;
            y = p.y;
            cout << "Using the assignment operator" << endl;
            return *this;
        }
};

And I tested when each constructor or method is called in my main program: 我测试了何时在主程序中调用每个构造函数或方法:

int main() {
    cout << "MyClass p" << endl; MyClass p; cout << endl;
    cout << "MyClass r(3.4)" << endl; MyClass r(3.4); cout << endl;
    cout << "MyClass s(r)" << endl; MyClass s(r); cout << endl;
    cout << "MyClass u = s" << endl; MyClass u = s; cout << endl;
    cout << "s = p" << endl; s = p; cout << endl;
}

Why is the copy constructor being used in the fourth example, MyClass u = s , instead of the assignment operator? 为什么在第四个示例MyClass u = s中使用拷贝构造函数,而不是赋值运算符?

EDIT 编辑

Including the output, as asked: 根据要求包括输出:

MyClass p
Using the default constructor

MyClass r(3.4)
Using the default constructor

MyClass s(r)
Using the copy constructor

MyClass u = s
Using the copy constructor

s = p
Using the assignment operator
Using the copy constructor

Because is not an actual assignment since you declare u at the same time. 因为这不是实际的分配,因为您同时声明了u。 Thus, the constructor is called instead of the assignment operator. 因此,调用了构造函数而不是赋值运算符。 And this is more efficient because if it wasn't for this feature there would have been the redundancy of calling first a default constructor and then the assignment operator. 而且这样做效率更高,因为如果不使用此功能,那么先调用一个默认构造函数,然后再调用赋值运算符将是多余的。 This would have evoked the creation of unwanted copies and thus would had deteriorate the performance of the C++ model significantly. 这会引起不必要的副本的创建,因此会大大降低C ++模型的性能。

Because that's the declaration and initialization of a variable, not the assigment of a value to an existing variable. 因为那是变量的声明和初始化,而不是将值分配给现有变量。 In the context of a variable declaration, = is just syntactic sugar for passing a parameter to the ctor. 在变量声明的上下文中,=只是用于将参数传递给ctor的语法糖。

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

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