C++学习三 模板类出错总结(Missing template arguments before 'L')

一、模板类的说明

  模板类有一个好处是可以放宽你输入的数据类型。

  比如有这样的一个函数:

 int add(int x, int y)
{
   return x+y;      
}

  这个函数对于int类型的x,y才适合,但是如果我们希望计算float类型的呢?

  这必须重新定义一个函数(函数重载也可以实现)

 float add(float x, float y)
{
   return x+y;      
}

  但是这样显然太麻烦,所以模板类可以解决这个问题

二、一个例子

  书上的一个例子用作说明

  

#include <iostream>
using namespace std;
template <typename Type> //这一步说明了你要定义一个模板类,数据类型名字是Type(比如可能是int, float,等等)
class Calc
{
public:
    Calc ();
    Type multiply (Type x, Type y);//类型都是Type
    Type add (Type x, Type y);//这里是函数的声明
};

template <typename Type> Calc<Type>::Calc ()
{ }

template <typename Type> Type Calc<Type>::multiply (Type x, Type y)
{
    return x * y;
}

template <typename Type> Type Calc<Type>::add (Type x, Type y)//这里是函数定义
{
    return x+y;
}
int main(void)
{
    Calc<int> person;
    int m=3;
    int n=2;
    int sum=person.add(m,n);
    cout<<"the result is "<<sum<<endl;
    return 0;
}

三、运行错误

  最开始初始化的时候,我是这样写的:

 Calc  person;

  但是失败了,结果如下:

   后来查了一下,发现需要在初始化的时候传入一个数据类型,告诉程序你要存储什么数据。

  有人给了一个解答:

  https://stackoverflow.com/questions/33413084/missing-template-arguments-before-l

  截图如下:

 讲的很透彻^-^

猜你喜欢

转载自www.cnblogs.com/fantianliang/p/11689297.html