7-1 函数重载(数据类型不同)
代码清单:
#include<iostream>
using namespace std;
class axxx
{
public:
void px(int n,int a[])
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n-i-1;j++)
{
int t;
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
}
void px(int n,double b[])
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n-i-1;j++)
{
double t;
if(b[j]>b[j+1])
{
t=b[j];
b[j]=b[j+1];
b[j+1]=t;
}
}
}
}
};
int main()
{
int n;
cin>>n;
axxx c1;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
double b[n];
for(int i=0;i<n;i++)
cin>>b[i];
c1.px(n,a);
c1.px(n,b);
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
for(int i=0;i<n;i++)
cout<<b[i]<<" ";
return 0;
}
运行结果截图
题目2(给出题目描述)
7-2 字符统计
代码清单:
#include<iostream>
using namespace std;
class Chartj{
public:
Chartj()
{
m_n1=0;
m_n2=0;
m_n3=0;
m_n4=0;
m_n5=0;
}
void sz()
{
m_n1+=1;
}
void dxzf()
{
m_n2+=1;
}
void xxzf()
{
m_n3+=1;
}
void kg()
{
m_n4+=1;
}
void qita()
{
m_n5+=1;
}
void print()
{
cout<<"n1="<<m_n1<<" ";
cout<<"n2="<<m_n2<<" ";
cout<<"n3="<<m_n3<<" ";
cout<<"n4="<<m_n4<<" ";
cout<<"n5="<<m_n5;
}
private:
int m_n1;
int m_n2;
int m_n3;
int m_n4;
int m_n5;
};
int main()
{
char arr[100];
int i=0,n=0;
Chartj c1;
scanf("%c",&arr[i]);
while(arr[i]!='\n')
{
if(arr[i]>='0'&&arr[i]<='9')
c1.sz();
else if(arr[i]>='A'&&arr[i]<='Z')
c1.dxzf();
else if(arr[i]>='a'&&arr[i]<='z')
c1.xxzf();
else if(arr[i]==' ')
c1.kg();
else
c1.qita();
i++;
scanf("%c",&arr[i]);
}
c1.print();
return 0;
}
运行结果截图
题目3(给出题目描述)
7-3 定义一个时间类Time
代码清单:
#include <iostream>
#include <string>
using namespace std;
class Time{
private:
int days;
int hours;
int minutes;
public:
Time(int d,int h, int m );
Time Sum(const Time & t);
void Show() const;
};
Time::Time(int d,int h, int m){
days=d;
hours=h;
minutes=m;
}
Time Time::Sum(const Time& t){
int a,b;
Time t4(0,0,0);
t4.minutes=(this->minutes+t.minutes)%60;
a=(this->minutes+t.minutes)/60;
t4.hours=(this->hours+t.hours+a)%24;
b=(this->hours+t.hours+a)/24;
t4.days=(this->days+t.days+b);
return t4;
}
void Time::Show() const{
cout<<days<<" "<<hours<<" "<<minutes;
}
int main(){
int d1,h1,m1,d2,h2,m2;
cin>>d1>>h1>>m1>>d2>>h2>>m2;
Time t1(d1,h1,m1),t2(d2,h2,m2),t3(0,0,0);
t3=t1.Sum(t2);
t3.Show();
return 0;
}运行结果截图
题目4(给出题目描述)
7-4 设计一个People类
代码清单:
#include<iostream>
#include<string>
using namespace std;
class People
{
public:
People(){};
People(string name,int age,int h,int w)
{
m_name=name;
m_age=age;
m_h=h;
m_w=w;
m_num+=1;
}
void print()
{
cout<<m_num<<endl;
}
private:
string m_name;
int m_age;
int m_h;
int m_w;
static int m_num;
};
int People::m_num=0;
int main()
{
string name;
int age;
int h;
int w;
while(cin>>name>>age>>h>>w&&name!="exit")
{
People p1(name,age,h,w);
}
People p1;
p1.print();
return 0;
}
运行结果截图