[C++] The reason why the copy constructor can't pass value

First of all, the copy constructor is a constructor that takes an object as a formal parameter.

The value cannot be passed because the formal parameter is a copy of the actual parameter in the process of passing the value.
Our parameter is an object, and the compiler calls the copy constructor at this time.
If the value is passed, we need to implement the copy constructor Call the copy constructor to copy the actual parameters. If the copy constructor has not been defined at this time, it will fall into infinite recursion...

class Date
{
    
    
public:
	Date(int year = 2021, int month = 2, int day = 3)
	{
    
    
		_year = year;
		_month = month;
		_day = day;
	}
	Date(const Date& d)
	//Date(Date d)
	//分别是穿引用和传值
	{
    
    
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
    
    
	Date d1;
	Date d2(d1);
	//copy构造函数
	return 0;
}

Guess you like

Origin blog.csdn.net/zhaocx111222333/article/details/113601413