此题的目的在于让我们深刻的理解c++中的 隐式类型转换;
006:奇怪的类复制
-
总时间限制:
- 1000ms 内存限制:
- 65536kB
-
描述
-
程序填空,使其输出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样例输入
None样例输出
9 22 5
#include <iostream>
using namespace std;
class Sample
{
public:
int v;
// 在此处补充你的代码
Sample(const Sample& a)
{
v = a.v+2;
}
Sample(int a=0)
{
v = a;
}
};
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;
}
#include <iostream>
using namespace std;
class Sample
{
public:
int v;
// 在此处补充你的代码
Sample(const Sample& a)
{
v = a.v+2;
}
Sample(int a=0)
{
v = a;
}
};
void PrintAndDouble(Sample o)
{
cout << o.v;
cout << endl;
}
int main()
{
Sample a(5); //此时 5 被赋值给了 a
Sample b = a; //然后这个临时对象的 .v 值 加上2 被赋值给了 b, b变成了7
PrintAndDouble(b); //然后这个对象b 被传入 print函数, 又发生了一次拷贝, 值再次加2变成了 9
Sample c = 20;
PrintAndDouble(c); //对象c 被传入 print函数, 又发生了一次拷贝, 值20加2变成了 22
Sample d;
d = a; //说明 d = a 没有发生拷贝,还是5
cout << d.v;
return 0;
}
这个题我们可以看出什么缺陷呢???