C + + learning experience--Reference mode copy class object
The importance of the reference is actually reflected in the function's formal parameters and the function's return value. General references are also only present in these two places.
The benefit of the reference method is that if it is reflected in the formal parameter, when the function is used, the argument is bound to be the initial taxiing parameter, and if not referenced, the system creates a copy of the argument to pass the value to the parameter, which can result in additional resource usage. In order to conserve resources, this effect is achieved by means of a reference, because the reference knowledge assigns the address of the argument to the formal parameter, and the parameter is treated as if it were an argument.
Here is an example of how the application is used: The importance of references is reflected in the formal parameters
#include <iostream>using namespacestd;classcbox{Private: Doublem_length; DoubleM_width; DoubleM_height; Public: CBox (DoubleLvDoubleWvDoubleHV): m_length{LV}, m_width{WV}, m_height{HV} {cout<<"Constrcurtor called."<<Endl; } CBox (ConstCBox &INITB): cbox{initb.m_length, Initb.m_width, initb.m_height} {cout<<"refrence called"<<Endl; } DoubleVolume () {returnm_length*m_height*M_width; }};int_tmain (intARGC, _tchar*argv[]) {CBox Box1 (10.0,10.0,10.0 ); CBox Mybox (box1);//mybox{box1}; same cout<<"Volume of box1="<< Box1.volume () <<Endl; cout<<"Volume of mybox="<< Mybox.volume () <<Endl; return 0;}
Results:
Analysis:
CBox box1 (10.0, 10.0, 10.0 ); CBox Mybox (box1);
1. The class definition for these two sentences automatically calls the constructor, and in the class declaration you can see that Constrcurtor called is displayed each time the constructor is called.
2. Because the definition mybox () takes box1 as the argument, does not create a copy for Box1, but is passed to the parameter by reference, the refrence called will appear when successfully passing the reference method
C + + learning experience--Reference mode copy class object