Problem F: 需要重载吗?
Description
定义一个类Overload,具有一个int类型的和一个char类型属性。在定义该类的对象时,如果不指定任何初始值,则输出:
Default constructor is called to make a = 0, c = ‘0’.
如果只给出一个int类型的初始值#,则输出:
First constructor is called to make a = #, c = ‘0’.
如果只给出一个char类型初始值,则输出:Secondconstructoriscalledtomakea=0,c=′,则输出:
Second constructor is called to make a = 0, c = ',则输出:Secondconstructoriscalledtomakea=0,c=′’.
如果给出一个int类型初始值#和一个char类型初始值KaTeX parse error: Expected 'EOF', got '#' at position 47: …ed to make a = #̲, c = '’.
Input
一个int类型的值和一个char类型的值。
Output
见样例。
Sample Input
10 a
Sample Output
Default constructor is called to make a = 0, c = ‘0’.
First constructor is called to make a = 10, c = ‘0’.
Second constructor is called to make a = 0, c = ‘a’.
Third constructor is called to make a = 10, c = ‘a’.
#include <bits/stdc++.h>
using namespace std;
class Overload
{
public:
int n;
char c;
Overload(int n1):n(n1),c('0')
{
cout<<"First constructor is called to make a = ";
cout<<n<<", c = '";
cout<<c;
cout<<"'.";
cout<<endl;
}
Overload(char c1):n(0),c(c1)
{
cout<<"Second constructor is called to make a = ";
cout<<n<<", c = '";
cout<<c;
cout<<"'.";
cout<<endl;
}
Overload(int n1,char c1):n(n1),c(c1)
{
cout<<"Third constructor is called to make a = ";
cout<<n<<", c = '";
cout<<c;
cout<<"'.";
cout<<endl;
}
Overload( ):n(0),c('0')
{
cout<<"Default constructor is called to make a = ";
cout<<n<<", c = '";
cout<<c;
cout<<"'.";
cout<<endl;
}
};
int main()
{
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
int i;
char ch;
cin>>i>>ch;
Overload t1, t2(i), t3(ch), t4(i, ch);
return 0;
}
2020/05/23
本文介绍了一个C++程序示例,展示了如何通过构造函数重载来创建类Overload的不同实例。根据输入的int和char类型的值,程序会调用相应的构造函数并输出调用信息。
379

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



