This example comes from learning video, not original.
First of all, we already know that we have four default functions when we create a class (there are actually 6, we'll explore later)
are: (Take the test class as an example) class test{Private:int value;}
1. Constructor: Test (int x=0)
2. Copy constructor: Test (const test& IT)
3. Assignment function test &operator (const test& IT)
4. destructor ~test ()
The following is a classic example of the process of applying four functions, which allows us to better understand the application code of these four functions as follows:
#include <iostream>using namespace Std;class test{private:int value;public:test () { value = 0; cout << "Defult Create Test:" << this << Endl;} Test (int t) { value = t; cout << "Create the Test:" << this << Endl;} Test (const test& IT) { value = It.value; cout << "Copy Create the test:" << this << Endl;} Test & operator= (const test& IT) { value = It.value; cout << this << "=" << &it << Endl; return *this; } ~test () { cout << "Destory the Test:" << this << Endl;} int Get_value () { return value;}}; Test Fun (test tp) {int x = Tp.get_value (); Test tmp (x); return TMP;} int main () {Test T1 (10); Test T2; Test t3 (); Although it is true, but cannot create the object, because the stipulation is to call the default constructor, you do not need parentheses, the parentheses will become the function declaration; t2 = Fun (t1); cout << "main end!" << Endl; return 0;}
analysis of the results performed:
The key point is:
1. The process of passing T1 to formal parameters
2. The process of returning a TMP argument
Subsequent additions: the fun () function is not the optimal method function, and is optimized in space and time:
<pre name= "code" class= "CPP" >/*1 not optimized before test fun (test TP)//value operation wastes time and space, so change to reference {int x = Tp.get_value (); Test tmp (x); return tmp;} *//*2 optimization of parameter passing Test fun (const test& TP)//value-added operation is a waste of time and space, so for reference//And since TP cannot change, we can add a const. This can significantly reduce the time space on {int x = Tp.get_value (); Test tmp (x); return tmp;} *///3 optimization of the return value test fun (const TEST & TP) {int x = Tp.get_value ();//test tmp (x);//return Tmp;return Test (x); Here the constructor is called directly to construct a nameless object to pass the value,//So the system will not create a temporary variable to store the object for the value operation}
"C + + Series Classic example" C + + default construction, copy, assignment, destructor four functions