注册 登录
编程论坛 C++教室

帮忙我解决error问题

晓宁 发布于 2011-09-18 21:36, 414 次点击
//This program demonstrates function templates.
#include<iostream>、
using namespace std;

template<class Type>
Type Max(Type x,Type y)
{
    return(x>y)?x:y;
}

template<class Type>
void Swap(Type& x,Type y)
{
    Type temp;
    temp=x;
    x=y;
    y=temp;
}

template<class TypeA,class TypeB>
TypeA Func(TypeA x,TypeB y)
{
    TypeA r;
    r= 3*x + 2*y;
    return r;
}

template<class Type>
Type Sum(Type[],int n)
{
    Type t=0;
    for(int i=0;i<n;++i)
        t+=a[i];
    return t;
}

int main()
{
    int i=3,j=5;
    double d=8.62;,e=4.14;

    float f_arr[6]={1.2,2.3,3.4,4.5,5.6,6.7};
    int i_arr[4]={4,5,6,7};

    cout<<"i="<<i<<"and j="<<j<<endl;
    cout<<"d="<<d<<"and e="<<e<<endl<<endl;
    cout<<"The larger of i and j is "<<Max(i,j)<<endl;
    cout<<"The larger of dand e is "<<Max(d,e)<<endl<<endl;
    Swap(i,j);
    Swap(d,e);
    cout<<"i="<<i<<"and j="<<j<<endl;
    cout<<"d="<<d<<"and e="<<e<<endl<<endl;
    cout<<"Func() applied to i and d is"<<Func(i,d)<<endl;
    cout<<"Func() applied ro d and i is"<<Func(d,i)<<endl<<endl;
    cout<<"The sum of f_arr[] is "<<Sum(f_arr,6)<<endl;
    cout<<"The sum of i_arr[] is "<<Sum(i_arr,4)<<endl;
    return 0;
}
2 回复
#2
玩出来的代码2011-09-18 21:41
楼下帮你,我路过。
#3
tisyang2011-09-19 09:20
程序代码:

//This program demonstrates function templates.
#include <iostream>
using namespace std;

template<class Type>
Type Max(Type x,Type y)
{
  return(x>y)?x:y;
}

template<class Type>
void Swap(Type& x,Type y)
{
  Type temp;
  temp=x;
  x=y;
  y=temp;
}

template<class TypeA,class TypeB>
TypeA Func(TypeA x,TypeB y)
{
  TypeA r;
  r= 3*x + 2*y;
  return r;
}

template<class Type>
Type Sum(Type *a,int n)
{
  Type t=0;
  for(int i=0;i<n;++i)
    t+=a[i];
  return t;
}

int main()
{
  int i=3,j=5;
  double d=8.62,e=4.14;

  float f_arr[6]={1.2,2.3,3.4,4.5,5.6,6.7};
  int i_arr[4]={4,5,6,7};

  cout<<"i="<<i<<"and j="<<j<<endl;
  cout<<"d="<<d<<"and e="<<e<<endl<<endl;
  cout<<"The larger of i and j is "<<Max(i,j)<<endl;
  cout<<"The larger of dand e is "<<Max(d,e)<<endl<<endl;
  Swap(i,j);
  Swap(d,e);
  cout<<"i="<<i<<"and j="<<j<<endl;
  cout<<"d="<<d<<"and e="<<e<<endl<<endl;
  cout<<"Func() applied to i and d is"<<Func(i,d)<<endl;
  cout<<"Func() applied ro d and i is"<<Func(d,i)<<endl<<endl;
  cout<<"The sum of f_arr[] is "<<Sum(f_arr,6)<<endl;
  cout<<"The sum of i_arr[] is "<<Sum(i_arr,4)<<endl;
  return 0;
}


注意书写的检查,头文件引用 #include 后需要空格
using namespace std 后的 分号 必须是英文标点。
Type Sum(Type[],int n)

这里建议不去使用 数组类型,改为指针可以提高适用范围。
double d=8.62;,e=4.14;
这里还是书写问题。。。。。。
自己多看看编译器提示的错误详细信息,一个一个去解决,培养自己解决问题的能力
1