【问题标题】:copy constructor not called未调用复制构造函数
【发布时间】:2012-01-31 07:22:34
【问题描述】:
#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 的复制构造函数没有被调用,我不知道为什么。我知道第二个假设有问题。 注意:这只是测试代码,所以不要过多讨论它的性能、可用​​性等。

【问题讨论】:

    标签: c++ copy-constructor


    【解决方案1】:

    你还没有为date定义一个拷贝构造函数,所以使用了隐式声明的拷贝构造函数。

    复制构造函数看起来像date(date const&amp; other) { }。您提供了一个默认构造函数 (date()) 和一个复制赋值运算符 (date&amp; operator=(const date&amp; a))。这些都不是复制构造函数。

    【讨论】:

    • 1.我肯定困了。我误解了date&amp; operator=(const date&amp; a) 来复制构造函数。 2.哇!人们真的住在这个网站上。喜欢迅速的反应。谢谢
    【解决方案2】:

    实际上,我在您的代码中没有找到复制构造函数。复制构造函数应该声明为 date(date&d),你只声明一个赋值操作。

    【讨论】:

      【解决方案3】:

      这不是拷贝构造函数,而是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) { /*... */ }
      

      【讨论】:

        猜你喜欢
        • 2012-02-06
        • 1970-01-01
        • 1970-01-01
        • 2021-05-14
        • 1970-01-01
        • 2018-10-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多