《数据结构》实验一: VC编程工具的灵活使用
一..实验目的
复习巩固VC编程环境的使用,以及C++模板设计。
1.回顾并掌握VC单文件结构程序设计过程。
2.回顾并掌握VC多文件工程设计过程
3.掌握VC程序调试过程。
4.回顾C++模板和模板的程序设计。
三.实验内容
1. 设计一个单文件结构程序完成从键盘输入两个数,输出二者的“和”和“积”的结果。要求如下:
1)设计函数来计算“和”和“积”,在主函数中调用,并能考虑重载函数,使整数和小数均能计算
#include <iostream>
using namespace std;
int sum(int x, int y)
{
int s;
s = x + y;
cout << x << "+" << y << "=" << s << endl;
cout << "used type int" << endl;
return s;
}
double sum(double x, double y)
{
double w;
w = x + y;
cout << x << "+" << y << "=" << w << endl;
cout << "used type double" << endl;
return w;
}
int mul(int x, int y)
{
int f;
f = x*y;
cout << x << "*" << y << "=" << f << endl;
cout << "used type int2" << endl;
return f;
}
double mul(double x, double y)
{
double m;
m = x*y;
cout << x << "*" << y << "=" << m << endl;
cout << "used type double2" << endl;
return m;
}
int main()
{
int x, y, c, k, q;
double a, b, l, j;
x = 1;
y = 6;
a = 4.3;
b = 6.5;
c = sum(1, 6);
k = mul(1, 6);
l = mul(4.3, 6.5);
j = sum(4.3, 6.5);
cin >> q;
return 0;
2.使用函数的模板来实现上述功能。
#include <iostream>
using namespace std;
template<class T>
T sum(T x, T y)
{
T s;
s = x + y;
return s;
}
template<class T>
T mul(T x, T y)
{
T s;
s = x* y;
return s;
}
int main()
{
int x, y, c, k;
double a, b;
x = 4;
y = 5;
a = 8.1;
b = 6.3;
cout << x << "+" << y << "=" << sum(x, y) << endl;
cout << a << "+" << b << "=" << sum(a, b) << endl;
cout << a << "*" << b << "=" << mul(a, b) << endl;
cout << x << "*" << y << "=" << mul(x, y) << endl;
cin >> k;
return 0;
}
3.使用一个类来实现上述功能。要求:
1)使用类模板
2)使用多文件:类的声明有头文件中;类的函数定义一个源文件中,在主程序文件中设计主函数程序,在实例化输出结果。
头文件
#ifndef FILENAME_H
#define FILENAME_H
template <class T>
class tem {
private:
T x, y;
public:
tem(T x, T y);
T multiply(T x, T y);
};
#endif
主函数
#include<iostream>
#include "FILE.h"
using namespace std;
template<class T> tem <T>::tem(T x, T y) { //构造函数,tem<T>中T为模板参数类型,tem<T>表示T类型的类
T s; //T表示数据类型,形参x和y的数据类型将实例化s的数据类型
s = x + y; //s保存x和y的运算结果
cout << x << "+" << y << "=" << s << endl;
}
template<class T> T tem<T>::multiply(T x, T y) { //multiply函数,T tem<T>中的T表示multiply方法的类型
T p;
p = (T)(x * y);
cout << x << "*" << y << "=" << p << endl;
return 0;
}
int main()
{
int t;
tem<int> S1(2, 3); //因为2和3是int型,模板将T实例化为int,这里相当于构造一个int型的对象
S1.multiply(2, 3); //S1对象调用multiply方法
tem<double> S2(2.1, 3.2); //与上面同理,只是实例成double型
S2.multiply(2.1, 3.2);
tem<float> S3(2.1f, 3.2f); //与上面同理,只是实例成double型
S3.multiply(2.1f, 3.2f);
cin >> t;
return 0;
}
本文详细介绍了使用C++模板和类实现数据结构实验的目的、内容及步骤,包括单文件结构程序设计、多文件工程设计、程序调试和C++模板程序设计等关键点。通过具体实例展示了如何计算整数和小数的和与积,以及如何使用模板和类进行功能复用。
629





