首页 > 解决方案 > C++ 复制 c'tor 现在确实采取了行动。不清楚为什么

问题描述

我有这个代码:

代码的输出是:

cons intcons op+ intcons ; copycons op+ intcons op+= ; get_val 3

class declaration::

#include<iostream>
using namespace std;

class Int {
public:
// constructors
Int() : val_(0) { cout << "cons "; }
Int(int n) { val_ = n; cout << "intcons "; }
Int(const Int &v) : val_(v.val_) { cout << "copycons "; }
Int(Int &&v_) { val_ = v_.val_; cout << "mov ctor " ; };

// operations
int get_val() {
    cout << "get_val "; return val_;
}
Int operator+(const Int &v) {
    cout << "op+ ";
    return Int(val_ + v.val_);
}
Int & operator=(const Int &v) {
    cout << "op= ";
    if (this != &v) { 
        val_ = v.val_; 
    }
    return *this;
}
Int & operator+=(const Int &v) {
    cout << "op+= ";
    val_ += v.val_;
    return *this;
}
private:
int val_; // value stored in this Int

};

这是主要的:

int main(){
Int zero;
Int one = zero + 1;
cout << ";\n";
Int two = zero;
two += one + one;
cout << ";\n";
cout << two.get_val() + 1; cout << endl;
return 0;
}

我正在查看代码输出,我可以同意发生的每个操作和每个输出。但有一件事我根本不清楚。我想知道,为什么在输出的第一行中没有使用 copy c'tor?

起初我虽然也许这是一个举动c'tor。然后我建立了一个,编译器似乎没有使用它。

谁能告诉我发生了什么事?谢谢你!

标签: c++operator-overloading

解决方案


我认为您将赋值运算符与复制构造函数混淆了。 Int two = zero;将导致调用复制构造函数。

two = zeroortwo = 1会导致赋值运算符被调用。

https://techdifferences.com/difference-between-copy-constructor-and-assignment-operator.html


推荐阅读