《数据结构》实验一: VC编程工具的灵活使用

《数据结构》实验一:      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的数据类型

= 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;

= (T)(* 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;

}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值