我在C++初學者,我使用資源說,下面的語句D3 = D1 + D2;調用以下:爲什麼被稱爲該聲明D1 = D2 + D3在C++中拷貝構造函數?
- +運算
- 默認構造函數
- 拷貝構造函數
- 析構函數
- 賦值運算符
- 析構函數
我不明白爲什麼複製構造函數在結果時被調用正被分配給之前聲明的變量以及爲什麼調用2個構造函數。
運營商如下:
A a=b,
when you return an object,
when you pass an object.
您+
運算符重載函數返回一個臨時object.which實際上將調用拷貝構造函數:當
date& date::operator=(const date& other)
{
cout << "Date assignment op" << endl;
if (this!=&other){
day=other.day;
month=other.month;
year=other.year;
}
return *this;
}
date date::operator+(const date& other) const
{
cout << "Date Operator + called" << endl;
date temp;
temp.day=day+other.day;
temp.month=month+other.month;
temp.year=year+other.year;
return temp;
}
類型d3; d3 = d1 + d2。這就是爲什麼我努力去理解它。 –
你的'+'運算符重載函數裏面有什麼?你可以發佈嗎? – Vijay
複製構造函數用於構造'd1 + d2'的(臨時)返回值。 – Mankarse