实验目的:
复习巩固VC编程环境的使用,以及C++模版设计。
1. 回顾并掌握VC单文件结构程序设计过程。
2. 回顾并掌握VC多文件设计过程。
3. 掌握VC程序调试过程
4. 回顾C++模板和模板的程序设计。
实验内容:
1.设计一个单文件结构程序完成从键盘输入两个数,输出二者的“和”和“积”的结果。要求如下:
1)设计函数来计算“和”和“积”,在主函数中调用,并能考虑重载函数,使整数和小数均能计算。
2)分别使用单步调试和断点调试来调试程序。并多次运行力求熟练调试方法。
2.使用函数的模板来实现上述功能。
3.使用一个类来实现上述功能。要求:
1)使用类模板
2)使用多文件:类的声明有头文件中;类的函数定义一个源文件中,在主程序文件中设计主函数程序,在实例化输出结果。
程序代码:
#include<iostream>
using namespace std;
int add(int a,int b)
{
return a + b;
}
int Indigestion(int a, int b)
{
return a*b;
}
Double add(double a, double b)
{
return a + b;
}
double Indigestion(double a, double b)
{
return a*b;
}
int main()
{ int a=0, b=0;
double x=0.0;
double y1=0.0;
char i='y';
while ('Y'==i||'y'==i)
{
cout << "pleast input two integer : ";
cin >> a >> b;
cout << "add= " << add(a,b) << endl;
cout << "Indigestion = " << Indigestion(a, b) << endl;
cout << "please input two decimal : ";
cin >> x >> y1;
cout << "add= " << add(x, y1) << endl;
cout << "Indigestion = " << Indigestion(x, y1) << endl;
cout << "again ? (y or n) : ";
cin >> i;
}
system("pause");
return 0;
}
程序代码二:
#include<iostream>
using namespace std;
template<typename T>
class Cal
{
public:
Cal(T , T);
~Cal();
T add();
T Indigestion ();
private:
T a, b;
};
template<typename T>
Cal<T>::~Cal()
{
}
template<typename T>
Cal<T>::Cal(T t1, T t2)
{
a = t1;
b = t2;
}
template<typename T>
T Cal<T>::add()
{
return a + b;
}
template<typename T>
T Cal<T>::Indigestion ()
{
return a*b;
}
int main()
{
int a=0, b=0;
double x=0.0, y=0.0;
cout<<"please input four number:"<<endl;
cin >> a >> b;
cin >> x >> y;
Cal<int>t(a, b);
Cal<double>d(x, y);
cout << "the sum is : " << t.add() << endl;
cout << "the Indigestion is : " << t.Indigestion () << endl;
cout << "the sum is : " << d.add() << endl;
cout << "the Indigestion is : " << d.Indigestion () << endl;
return 0;
}
}
程序代码三:
//moban.h
template<typename
T>
class Cal
{
public:
Cal (
T,
T);
~Cal ();
T add();
T
Indigestion();
private:
T a, b;
};
#include"类模版.h"
#include<iostream>
template<typename
T>
Cal<
T>::~Cal ()
{}
template<typename
T>
Cal<
T>::Cal (
T t1,
T t2)
{
a = t1;
b = t2;
}
template<typename
T>
T Cal<
T>::add()
{
return a + b;
}
template<typename
T>
T Cal<
T>::
Indigestion ()
{
return a*b;
}
//main.cpp
#include"moban.h"
#include<iostream>
using
namespace
std;
int main()
{
int a=0, b=0;
double x=0.0, y=0.0;
cout<<
"please input four numbers : "<<endl;
cin >> a >> b;
cin >> x >> y;
Cal<
int>t(a, b);
Cal<
double>d(x, y);
cout <<
"the sum is : " << t.add() << endl;
cout <<
"the Indigestion is : " << t.
Indigestion () << endl;
cout <<
"the sum is : " << d.add() << endl;
cout <<
"the Indigestion is : " << d.
Indigestion () << endl;
return
0;
}