C++ constructor and copy constructor

1. Constructor

There is a special member function in a class whose name is the same as the class name. When creating a class object, this special member function will be automatically called by the system. This function is called a copy constructor. It can be simply understood that the meaning of the constructor is to initialize the member variables of the object in the class.

Note that the constructor has no return value, and multiple constructors are allowed in a class . The following provides two constructor definition methods:

	Time(int hour, int minute, int second):Hour(hour),Minute(minute),Second(second)
	{
		cout << "构造函数的调用" << endl;
	}
	Time(int hour, int minute, int second)
	{
		Hour = hour;
		Minute = minute;
		Second = second;
	}
    Time time1(10,10,10);//构造函数的调用

Although multiple constructors are allowed in a class, the compiler must distinguish the difference between different constructors, otherwise an error will be reported. The above code is not allowed to exist at the same time.

Time time2 = time1;//这种不调用构造函数

The above code actually calls the copy constructor. Now let's explain the copy constructor.

2. Copy constructor

	Time(const Time& mytime)
	{
		Hour = mytime.Hour;
		Minute = mytime.Minute;
		Second = mytime.Second;
		cout << "拷贝构造函数的调用" << endl;
	}
	Time(const Time& mytime):Hour(mytime.Hour),Minute(mytime.Minute),Second(mytime.Second)
	{
		cout << "拷贝构造函数的调用" << endl;
	}

The above are two ways of writing the copy constructor, and the default copy constructor of the system is probably like this.

The first parameter of the copy constructor replaces const. Generally speaking, the first parameter of the copy constructor is decorated with const, so that one less temporary variable can be created and efficiency can be improved.

If you don't know whether to call the copy constructor or the constructor when defining the object, you can print some statements in the two functions to help you confirm whether to call the function.

Call the copy constructor when passing an object as an argument to a function:

void test(Time m)
{
	return ;
}//调用拷贝构造函数
void test(Time& m)
{
	return ;
}//不会调用拷贝构造函数

The copy constructor is called when returning a class object from a function. (may be invisible to compiler optimizations).

 

Guess you like

Origin blog.csdn.net/m0_74358683/article/details/131674017