gpt4 book ai didi

c++ - 未调用复制构造函数

转载 作者:太空宇宙 更新时间:2023-11-04 16:29:03 25 4
gpt4 key购买 nike

#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 的复制构造函数没有被调用,我不知道为什么。我知道第二个假设有问题。 注意:这只是测试代码,所以不要超过它的性能、可用​​性等。

最佳答案

您还没有为 date 定义复制构造函数,因此使用了隐式声明的复制构造函数。

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

关于c++ - 未调用复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9075856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com