C++-习题6 多态性与模板

1. (30分) C+±6-1-函数模板

题目描述
编写一个函数模板,求数组中的最大元素,并写出调用此函数模板的主函数,使得函数调用时,数组的类型可以是int型、double型和string类型。数组中元素个数3≤n≤20
主函数中,先从键盘输入各种类型数组的长度,再输入数组元素的值,调用函数求出最大值,再输出。

输入描述
输入共分6行
int型数组元素的个数
int型数组元素的值
double型数组元素的个数
double型数组元素的值
string类型数组元素的个数
string数组元素的值

输出描述
三行
int型数组中元素的最大值
double型数组中元素的最大值
string型数组中元素的最大值

输入样例
5
78 96 -12 52 856
6
3.2 5.6 89.2 -3.2 46.2 63.47
5
hello world example virtual char

输出样例
856
89.2
world

用户代码

#include<iostream>
#include<string>
using namespace std;
template<typename T>
T max(T *x,int n)
{
	T y=x[0];
	for(int i=0;i<n;i++)
		if(x[i]>y)
			y=x[i];
	return y;
}
int main()
{
	int x,y,z,i;
	int a[20];
	double b[20];
	string c[20];
	cin>>x;
	for(i=0;i<x;i++)
		cin>>a[i];
	cin>>y;
	for(i=0;i<y;i++)
		cin>>b[i];
	cin>>z;
	for(i=0;i<z;i++)
		cin>>c[i];
	cout<<max(a,x)<<endl;
	cout<<max(b,y)<<endl;
	cout<<max(c,z)<<endl;
	return 0;
}

2. (30分) C+±6-2-类与对象及静态数据成员 题目描述

某商店经销一种货物,货物成箱购进,成箱卖出,购进和卖出时均以重量为单位,各箱的重量不一样,因此,商店需要记录下库存货物的总重量,现要求用C++编程,模拟商店货物购进和卖出的情况。
主函数中,先输出商店货物的初始重量(初始为0),再增加两箱货物,货物重量由键盘输入,输出增加后商店货物总重量。
提示:需要定义静态数据成员存储库存货物的总重量。

输入描述
两箱货物的重量

输出描述
商店货物原始总重量
增加两箱货物后的总重量

输入样例
56
54

输出样例
货物的初始重量:0
此时货物的重量:110

用户代码

#include<iostream>
using namespace std;
class A
{
public:
	A(int a){b=a;c+=a;}
	static void show()
	{
		cout<<c;
	}
private:
	int b;
	static int c;
};
int A::c=0;
int main()
{
	int a,b;
	cin>>a>>b;
	cout<<"货物的初始重量:";
	A::show();
	A x(a),y(b);
        cout<<endl;
	cout<<"此时货物的重量:";
	A::show();
	return 0;
}
 

3. (40分) C+±6-3-Point3D运算符重载函数

题目描述
编程:定义描述三维坐标点的类Point3D,重载”++”、”–”、”+”运算符,要求用成员函数实现后置++运算符,用友元运算符实现前置–运算和加法运算符重载。
编写主函数,定义Point3D类对象p1、p2(p1、p2的值均从键盘输入)、p(使用默认值,默认值为0,0,0),执行
p = p1++; 输出p、p1的值
p = --p2; 输出p、p2的值
p = p1 + p2; 输出p的值

输入描述
两行
第一个三维点的坐标
第二个三维点的坐标

输出描述
执行以下操作后:
p = p1++; 输出p、p1的值
p = --p2; 输出p、p2的值
p = p1 + p2; 输出p的值

输入样例
3 5 4
7 1 5

输出样例
p1=(4,6,5)
p=(3,5,4)
p2=(6,0,4)
p=(6,0,4)
p=(10,6,9)

用户代码

#include<iostream>
using namespace std;
class Point3D
{
public:
	Point3D(int a=0,int b=0,int c=0)
	{
		x=a;y=b;z=c;
	}
	Point3D operator++(int)
	{
		Point3D A;
		A.x=x++;A.y=y++;A.z=z++;
		return A;
	}
	friend Point3D operator--(Point3D &A)
	{
		Point3D B;
		B.x=--A.x;B.y=--A.y;B.z=--A.z;
		return B;
	}
	friend Point3D operator+(Point3D A,Point3D B)
	{
		Point3D C;
		C.x=A.x+B.x;
		C.y=A.y+B.y;
		C.z=A.z+B.z;
		return C;
	}
	void show()
	{
		cout<<"=("<<x<<","<<y<<","<<z<<")"<<endl;
	}
private:
	int x,y,z;
};
int main()
{
	int a,b,c,d,e,f;
	cin>>a>>b>>c>>d>>e>>f;
	Point3D p;
	Point3D p1(a,b,c),p2(d,e,f);
	p=p1++;
	cout<<"p1";
	p1.show();
	cout<<"p";
	p.show();
	p=--p2;
	cout<<"p2";
	p2.show();
	cout<<"p";
	p.show();
	p=p1+p2;
	cout<<"p";
	p.show();
	return 0;
}
发布了37 篇原创文章 · 获赞 10 · 访问量 756

猜你喜欢

转载自blog.csdn.net/qq_43608850/article/details/104317813