类模板成员函数默认值问题:an out-of-line definition of a member of a class template cannot have default arguments

template <typename T>
class A {
    void fun(int a = 0);
};

template<typename T>
void A<T>::fun(int a = 0) {
    /*
    */
}

对于类似上文代码,VS编译器会报 “an out-of-line definition of a member of a class template cannot have default arguments”错误。

其原因在于:带有默认参数值的模板类成员不能在类外进行定义,修改方式有两种。

第一种在类内进行定义:

template <typename T>
class A {
    void fun(int a = 0){
       /*
      */
    }
};

第二种在类外进行定义时,将默认值去掉:

template <typename T>
class A {
    void fun(int a = 0);
};

template<typename T>
void A<T>::fun(int a /*= 0*/) {
    /*
    */
}

猜你喜欢

转载自www.cnblogs.com/code-wangjun/p/9107867.html