c++考试模版(2)

2020-06-21 16:07

gehongxiang

}

void main() {

double a=3.56,b=8.23;

char s1[]=\ cout<<\输出结果:\

cout<<\中较小者:\ cout<<\中较小者:\ }

输出结果:

3.56,8.23中较小者:3.56 Hello,Good中较小者:Good

题4.设计一个数组类模板Array,其中包含重载下标运算符函数,并由此产生模板类Array和Array,使用一些测试数据对其进行测试。 解:

本题程序如下: #include #include template class Array {

T *elems; int size; public:

Array(int s); // 构造函数 ~Array();

T& operator[](int); // 重载下标运算符 void operator=(T); // 重载等号运算符 };

template Array::Array(int s) {

size=s;

elems=new T[size]; for(int i=0;i

template Array::~Array() {

delete elems; }

template

gehongxiang

T& Array::operator[](int index) {

return elems[index]; }

template

void Array::operator=(T temp) {

for(int i=0;i

void main() {

int i,n=10;

Array arr1(n); // 产生整型模板类及其对象arr1 Array arr2(n); // 产生字符型模板类及其对象arr2 for(i=0;i

arr1[i]=’a’+i; // 调用重载运算符 arr2[i]=’a’+i; }

cout<<\码 字符\ for(i=0;i

cout<本程序的执行结果如下: ASCII码 字符 97 a 98 b 99 c 100 d 101 e 102 f 103 g 104 h 105 i 106 j

题 5. 一个Sample类模板的私有数据成员为T n,在该类模板中设计一个operator==重载运算符函数 ,用于比较各对象的n数据是否相等。 解:

本题程序如下: #include template class Sample

gehongxiang

{ T n; public:

Sample(T i){n=i;}

int operator==(Sample &); };

template

int Sample::operator==(Sample &s) {

if(n==s.n) return 1; else return 0; }

void main() {

Sample s1(2),s2(3);

cout<<\与s2的数据成员\相等\不相等\ Samples3(2.5),s4(2.5);

cout<<\与s4的数据成员\相等\不相等\ }

本程序的运行结果如下: s1与s2的数据成员不相等 s3与S4的数据成员相等

题 6. 对第3章的例3.5进行修改,只设计一个Sample类,其数据和方法均包含在该类中,而且使用类模板的方式实现。 #include #define Max 100 template class Sample {

T A[Max]; int n;

void qsort(int l,int h); // 私有成员,由quicksort()成员调用 public:

Sample(){n=0;}

void getdata(); // 获取数据 void insertsort(); // 插入排序 void Shellsort(); // 希尔排序 void bubblesort(); // 冒泡排序 void quicksort(); // 快速排序 void selectsort(); // 选择排序 void disp();

gehongxiang

};

template

void Sample::getdata() {

cout<<\元素个数:\ cin>>n;

for(int i=0;i

cout<<\输入第\个数据:\ cin>>A[i]; } }

template

void Sample::insertsort() // 插入排序 { int i,j; T temp;

for(i=1;i

temp=A[i]; j=i-1;

while(temp

A[j+1]=A[j]; j--; }

A[j+1]=temp; } }

template

void Sample::Shellsort() // 希尔排序 {

int i,j,gap; T temp; gap=n/2; while(gap>0) {

for(i=gap;i

j=i-gap;

while(j>=gap) if(A[j]>A[j+gap]) {

temp=A[j];

gehongxiang

A[j]=A[j+gap]; A[j+gap]=temp; j=j-gap; }

else j=0; }

gap=gap/2; } }

template

void Sample::bubblesort() // 冒泡排序 { int i,j; T temp;

for(i=0;i=i+1;j--) if(A[j]

temp=A[j]; A[j]=A[j-1]; A[j-1]=temp; } }

template

void Sample::quicksort() // 快速排序 {

qsort(0,n-1); }

template

void Sample::qsort(int l,int h) {

int i=l,j=h; T temp; if(l

temp=A[l]; do{

while(j>i&&A[j]>=temp) j--; if(i

A[i]=A[j]; i++; }


c++考试模版(2).doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:20120602九重锦沙盘说辞

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: