题目描述
某个类包含一个整型数据成员.程序运行时若输入0表示用缺省方式定义一个类对象;输入1及一个整数表示用带一个参数的构造函数构造一个类对象;输入2及一个整数表示构造2个类对象,一个用输入的整数构造,另一个用前一个对象构造。试完成该类的定义和实现。
输入
测试数据的组数 t
第一组数
第二组数
…
输出
第一个对象构造输出
第二个对象构造输出
…
输入样例
3
0
1 10
2 20
Constructed by default, value = 0
Constructed using one argument constructor, value = 10
Constructed using one argument constructor, value = 20
Constructed using copy constructor, value = 20
#include<iostream>
using namespace std;
class construct
{
int x;
public:
construct()
{
x=0;
cout<<"Constructed by default, value = "<<x<<endl;
}
construct(int n)
{
x=n;
cout<<"Constructed using one argument constructor, value = ";
cout<<x<<endl;
}
construct(construct &c)
{
x=c.x;
cout<<"Constructed using copy constructor, value = ";
cout<<x<<endl;
}
};
int main()
{
int t,x,i;
cin>>t;
while(t--)
{
cin>>x;
if(x==0)
{
construct c1;
}
else if(x==1)
{
cin>>i;
construct c2(i);
}
else if(x==2)
{
cin>>i;
construct c3(i);
construct c4(c3);
}
}
return 0;
}
本文展示了如何使用C++定义一个类,包括默认构造函数、带有参数的构造函数和拷贝构造函数。程序根据输入的指令创建不同类型的类对象,并输出相应的构造信息。测试案例中,类对象的构造过程被详细呈现。
624

被折叠的 条评论
为什么被折叠?



