c++ - 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。然后我建立了一个,编译器似乎没有使用它。
谁能告诉我发生了什么事?谢谢你!
解决方案
我认为您将赋值运算符与复制构造函数混淆了。
Int two = zero;
将导致调用复制构造函数。
two = zero
ortwo = 1
会导致赋值运算符被调用。
https://techdifferences.com/difference-between-copy-constructor-and-assignment-operator.html
推荐阅读
- java - 限制在 firebase 实时数据库中添加的子项数量
- java - 如何在android studio中的背景图像上显示gif
- angular - 以 Angular 形式提交
- javascript - 与多个 index.html 反应
- java - 装饰器模式可以用行为模式代替来解决问题吗?
- mongodb - 无法在项目上执行目标 io.swagger:swagger-codegen-maven-plugin:2.2.3:generate (default) 代码生成失败
- ios - 通知未收到 iOS
- firebase - 添加 Firebase 存储包后 Unity android 无法构建
- asp.net-mvc - asp.net mvc 应用程序中 bin\roslyn\csc.exe 中的 exe 文件不允许在托管服务器中使用。如何解决这个问题?
- reactjs - 如何在令牌过期时创建注销