Quiz 006: Strange Class Copy

describe

The program fills in the blanks to make it output 9 22 5

#include <iostream>
using namespace std;
class Sample {
    
    
public:
	int v;
// 在此处补充你的代码
};
void PrintAndDouble(Sample o)
{
    
    
	cout << o.v;
	cout << endl;
}
int main()
{
    
    
	Sample a(5);
	Sample b = a;
	PrintAndDouble(b);
	Sample c = 20;
	PrintAndDouble(c);
	Sample d;
	d = a;
	cout << d.v;
	return 0;
}
analysis:
  1. Observing several constructors, you will find that what you need are conversion constructors and copy constructors.
  2. Among them d = ais the default assignment operator, so it can be seen that a is 5 after the conversion constructor is created. So there is no change in the conversion constructor.
  3. The b copy constructor takes a as the parameter, and then becomes 9. 5 becomes 9, because the parameter also needs to be copied to generate temporary variables, and the temporary variables are copied to b after the operation, so the two copies are equal to 4, so copy The constructor is plus 4.
  4. c is 22, 20 conversion constructor to generate a temporary object, and then copy to c, so one conversion and one copy are used.
years:
Sample(int i=0):v(i){
    
    }
	Sample(const Sample& s)
	{
    
    
		v=s.v+2;
	}

Guess you like

Origin blog.csdn.net/ZmJ6666/article/details/108553546