#include <iostream>
int main(void)
{
class date {
private:
int day;
int month;
int year;
public:
date() { std::cout << "default constructor called" << std::endl; }
date& operator=(const date& a) { std::cout << "copy constructor called" << std::endl; day=a.day; month=a.month; year=a.year; }
date(int d ,int m ,int y ) : day(d),month(m),year(y){ std::cout << "constructor called" << std::endl; }
void p_date(){ std::cout << "day=" << day << ",month=" << month << ",year=" << year << std::endl; }
date& add_day(int d) { day += d; return *this;}
date& add_month(int d) { month += d;return *this; }
date& add_year(int d) { year += d;return *this; }
};
class cdate {
date n;
public:
cdate(date b) : n(b) { std::cout << "cdate constructor called" << std::endl;}
void p_cdate() { n.p_date(); }
};
cdate ncdate(date(30,1,2012));
ncdate.p_cdate();
}
當我們在這個代碼實例ncdate
:拷貝構造函數不叫
- 當我們調用
cdate ncdate(date(30,1,2012));
- 創建的臨時約會對象的話,我希望呼叫
n = b
,並期望n
的拷貝構造函數是調用。
n
的拷貝構造函數沒有被調用,我無法弄清楚爲什麼。我知道第二個假設有錯誤。 注:這是測試代碼只所以不要超過它的性能,可用性等
1.我絕對困。我誤解'date&operator =(const date&a)'來複制構造函數。 2. WOW!人們真的活在這個網站上。就像即時響應一樣。謝謝 – PnotNP 2012-01-31 07:35:21