2012-01-31 67 views
0
#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拷貝構造函數不叫

  1. 當我們調用cdate ncdate(date(30,1,2012));
  2. 創建的臨時約會對象的話,我希望呼叫n = b,並期望n的拷貝構造函數是調用。

n的拷貝構造函數沒有被調用,我無法弄清楚爲什麼。我知道第二個假設有錯誤。 注:這是測試代碼只所以不要超過它的性能,可用性等

回答

5

您尚未date定義拷貝構造函數,因此使用隱式聲明的拷貝構造函數。

複製構造函數看起來像date(date const& other) { }。您提供了默認構造函數(date())和複製賦值運算符(date& operator=(const date& a))。這些都不是複製構造函數。

+0

1.我絕對困。我誤解'date&operator =(const date&a)'來複制構造函數。 2. WOW!人們真的活在這個網站上。就像即時響應一樣。謝謝 – PnotNP 2012-01-31 07:35:21

0

實際上,我沒有在代碼中找到拷貝構造函數。複製構造函數應聲明爲日期(日期& d),則只聲明一個賦值操作。

0

這不是複製構造函數,而是operator =。

date& operator=(const date& a) { std::cout << "copy constructor called" << std::endl; day=a.day; month=a.month; year=a.year; } 

一個拷貝構造函數應該是這樣的:

date(const date& a) { /*... */ }