面向对象程序设计-实验十二
6-1 数组排序输出(函数模板)
对于输入的每一批数,按从小到大排序后输出。
一行输入为一批数,第一个输入为数据类型(1表示整数,2表示字符型数,3表示有一位小数的浮点数,4表示字符串,0表示输入结束),第二个输入为该批数的数量size(0<size<=10),接下来为size个指定类型的数据。
输出将从小到大顺序输出数据。
代码清单:
#include <iostream>
#include <string>
using namespace std;
/* 请在这里填写答案 */
template<class TA>
void sort(TA* a,int size)
{
for(int k=0;k<size;k++)
{
cin>>a[k];
}
TA temp=a[0];
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
template <class T>
void display(T* a, int size){
for(int i=0; i<size-1; i++) cout<<a[i]<<' ';
cout<<a[size-1]<<endl;
}
int main() {
const int SIZE=10;
int a[SIZE];
char b[SIZE];
double c[SIZE];
string d[SIZE];
int ty, size;
cin>>ty;
while(ty>0){
cin>>size;
switch(ty){
case 1:sort(a,size); display(a,size); break;
case 2:sort(b,size); display(b,size); break;
case 3:sort(c,size); display(c,size); break;
case 4:sort(d,size); display(d,size); break;
}
cin>>ty;
}
return 0;
}
运行结果截图
题目2(给出题目描述)
7-1 车辆计费#include<iostream>
代码清单:
#include<string>
using namespace std;
class Vehicle{
protected:
string NO;
public:
Vehicle(string str)
{
NO=str;
}
virtual void display()=0;
};
class Car:public Vehicle{
int num;
int kg;
public:
Car(string str,int _num,int _kg):Vehicle(str)
{
num=_num;
kg=_kg;
}
virtual void display()
{
cout<<NO<<" "<<num*8+kg*2<<endl;
}
};
class Truck:public Vehicle{
int kg;
public:
Truck(string str,int _kg):Vehicle(str)
{
kg=_kg;
}
virtual void display()
{
cout<<NO<<" "<<kg*5<<endl;
}
};
class Bus:public Vehicle{
int num;
public:
Bus(string str,int _num):Vehicle(str)
{
num=_num;
}
virtual void display()
{
cout<<NO<<" "<<num*3<<endl;
}
};
int main()
{
Vehicle *pv[10];
string str;
int t,num,kg,i=0;
cin>>t;
while(t!=0)
{
cin>>str;
if(t==1)
{
cin>>num>>kg;
pv[i]=new Car(str,num,kg);
}else if(t==2){
cin>>kg;
pv[i]=new Truck(str,kg);
}else if(t==3){
cin>>num;
pv[i]=new Bus(str,num);
}
pv[i]->display();
i++;
cin>>t;
}
return 0;
}
运行结果截图
题目3给出题目描述)
7-2 复数类模板
代码清单:
#include <iostream>
using namespace std;
template <class TA>
class Complex
{
private:
TA real;
TA image;
public:
Complex(TA r = 0, TA i = 0) : real(r), image(i) { };
void Show() const;
Complex Add(const Complex& z2);
};
template <class TA>
void Complex<TA>::Show() const
{
cout << "(" << real << ", " << image << ")";
}
template <class TA>
Complex<TA> Complex<TA>::Add(const Complex& z2)
{
float r, i;
r = this->real + z2.real;
i = this->image + z2.image;
Complex z(r, i);
return z;
}
int main()
{
float x1=0, x2=0, y1=0, y2=0;
cin >> x1 >> y1;
cin >> x2 >> y2;
Complex<float> z1(x1, y1), z2(x2, y2);
(z1.Add(z2)).Show();
return 0;
}
运行结果截图