002:奇怪的类复制

程序填空,使其输出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;
}

输入 

输出

9

22

5

思路:简单分析一下,题目要求我们补充类的构造函数。//a的复制构造函数没有被调用,构造函数执行初始化, //b的复制构造函数被调用了两次,输出9 //c的复制构造函数被调用了一次输出22 //d的复制构造函数没有被调用,d的值由a赋予

不难得出构造函数由形参赋值,复制构造函数+2

#include <cstring>
#include <iostream>
#include <iomanip>
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <string>
#include <cstdio>
#include <cstring>
#include <sstream>
#include <cstdlib>
using namespace std;
class Sample
{
 public:
    int v;
    Sample(const Sample &a)
    {
        v = a.v + 2;
    }
    Sample(int c=0)
    {
        v = c;
    }
};
void PrintAndDouble(Sample o)
{
    cout<<o.v;
    cout<<endl;
}
int main()
{
    Sample a(5);//a的复制构造函数没有被调用,构造函数执行
    Sample b = a;
    PrintAndDouble(b);//9 b的复制构造函数被调用了两次
    Sample c = 20;
    PrintAndDouble(c);//22 c的复制构造函数被调用了一次
    Sample d;
    d = a;
	  cout << d.v;//5 d的复制构造函数没有被调用,d的值由a赋予
	  return 0;
    
    
}

  

posted @ 2020-08-27 10:08  MEYE66  阅读(262)  评论(0)    收藏  举报