2012-01-31 241 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) { /*... */ }