当前位置:编程学习 > C/C++ >>

求c++编程..........

1.阅读下列程序,写出程序的功能,然后使用模板函数改写该程序并上机验证。

#include<iostream.h>

void exchange(int &x,int &y,int &z)

{

    int temp1=y,temp2=z;

    y=x; z=temp1; x=temp2;

}

void exchange(float &x,float &y,float &z)

{

    float temp1=y,temp2=z;

    y=x; z=temp1; x=temp2;

}

void exchange(double &x,double &y,double &z)

{

    double temp1=y,temp2=z;

    y=x; z=temp1; x=temp2;

}

void main()

{

    int i,j,k;

    cout<<"i,j,k=";

    cin>>i>>j>>k;

    exchange(i,j,k);

    cout<<i<<'\t'<<j<<'\t'<<k<<endl;

 

    float a,b,c;

    cout<<"a,b,c=";

    cin>>a>>b>>c;

    exchange(a,b,c);

    cout<<a<<'\t'<<b<<'\t'<<c<<endl;

 

    double u,v,w;

    cout<<"u,v,w=";

    cin>>u>>v>>w;

    exchange(u,v,w);

    cout<<u<<'\t'<<v<<'\t'<<w<<endl;

}

答案:
#include<iostream>
using namespace std;
template<class T>
void exchange(T &x,T &y,T &z)
{
    T temp1=y,temp2=z;
    y=x; z=temp1; x=temp2;
}
void main()
{
    int i,j,k;
    cout<<"i,j,k=";
    cin>>i>>j>>k;
    exchange(i,j,k);
    cout<<i<<'\t'<<j<<'\t'<<k<<endl;
 
    float a,b,c;
    cout<<"a,b,c=";
    cin>>a>>b>>c;
    exchange(a,b,c);
    cout<<a<<'\t'<<b<<'\t'<<c<<endl;
 
    double u,v,w;
    cout<<"u,v,w=";
    cin>>u>>v>>w;
    exchange(u,v,w);
    cout<<u<<'\t'<<v<<'\t'<<w<<endl;
}
就是值交换,前面的三个
exchange函数 是重载函数,分别用于不同的类型,至于改写成类模版,一楼那位正解

上一个:跪求C++编程。
下一个:用c++编程

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,