实验目的
复习巩固VC编程环境的使用,以及C++模板设计。
1.回顾并掌握VC单文件结构程序设计过程。
2.回顾并掌握VC多文件工程设计过程
3.掌握VC程序调试过程。
4.回顾C++模板和模板的程序设计。
实验内容
1. 设计一个单文件结构程序完成从键盘输入两个数,输出二者的“和”和“积”的结果。要求如下:
1)设计函数来计算“和”和“积”,在主函数中调用,并能考虑重载函数,使整数和小数均能计算。
2)分别使用单步调试和断点调试来调试程序。并多次运行力求熟练调试方法。
代码:
#include <iostream>
using namespace std;
void he(int x,int y)
{
int sum=0;
sum=x+y;
cout<<"两个数的和为:"<<sum<<endl;
}
void he(double x,double y)
{
double sum=0;
sum=x+y;
cout<<"两个数的和为:"<<sum<<endl;
}
void ji(int x,int y)
{
int sum=1;
sum=x*y;
cout<<"两个数的积为:"<<sum<<endl;
}
void ji(double x,double y)
{
double sum=1;
sum=x*y;
cout<<"两个数的积为:"<<sum<<endl;
}
int main()
{
float a,b;
cout<<"输入两个数:";
cin>>a>>b;
he(a,b);
ji(a,b);
cout<<endl;
return 0;
}
调试结果:
图1
2.使用函数的模板来实现上述功能。
代码:
#include<iostream>
using namespace std;
template<class T1,class T2>
T1 plus(T1 x,T2 y)
{
T1 he;
he=x+y;
cout<<"两个数的和为:"<<he<<endl;
return he;
}
template<class G1,class G2>
G1 mul(G1 x,G2 y)
{
G1 ji;
ji=x*y;
cout<<"两个数的积为:"<<ji<<endl;
return ji;
}
int main()
{
float m1,m2;
cout<<"输入两个数:";
cin>>m1>>m2;
plus(m1,m2);
mul(m1,m2);
return 0;
}
调试结果:参考 图1
3.使用一个类来实现上述功能。要求:
1)使用类模板
2)使用多文件:类的声明有头文件中;类的函数定义一个源文件中,在主程序文件中设计主函数程序,在实例化输出结果。
源文件:
#include <iostream>
using namespace std;
#include"CA.H"
int main()
{
float m1,m2;
cout<<"输入两个数:";
cin>>m1>>m2;
Ca<float>a;
Ca<float>b;
a.plus(m1,m2);
a.mul(m1,m2);
return 0;
}
头文件:
#include <iostream>
using namespace std;
template <class T>
class Ca
{
public:
void plus(T x,T y)
{
T he;
he=x+y;
cout<<"两个数的和为:"<<he<<endl;
}
void mul(T x,T y)
{
T ji;
ji=x*y;
cout<<"两个数的积为:"<<ji<<endl;
}
};
调试结果:参考 图1