c++ - 使用类定义之外的默认参数定义的默认构造函数,为什么会这样?涉及的模板会发生什么?

标签 c++ class templates default-value default-constructor

我知道这是一种错误的形式,默认值应该在声明中指定,但如果你愿意,请允许我花点时间……为什么要编译?到底发生了什么?

#include <iostream>
using namespace std;

class test
{
public:
    test(int n);
};

test::test(int n = 666)
{
    cout << n;
}

int main()
{
    test t;

    cin.sync();
    cin.ignore();

    return 0;
}

输出: 666

.. 模板如何影响同一段代码?

template <class T>
class test
{
public:
    test(int n);
};

template <class T>
test<T>::test(int n = 666)
{
    cout << n;
}

int main()
{
    test<int> t;

    cin.sync();
    cin.ignore();

    return 0;
}

错误:没有合适的默认构造函数可用

感谢您的宝贵时间!

最佳答案

看起来 C++ 规范特别允许第一种情况而不允许第二种情况!

引自 C++ 规范 (§8.3.6/4):

For non-template functions, default arguments can be added in later declarations of a function in the same scope.

所以看起来对于非模板函数,你确实可以稍后引入默认参数。不过不知道为什么这对模板不起作用!

关于c++ - 使用类定义之外的默认参数定义的默认构造函数,为什么会这样?涉及的模板会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6805507/

相关文章:

c++ - 将二维数组传递给 C++ 中的函数

c++ - 有没有一种方法来存储通用的模板化函数指针?

c++ - 变量作为 C++ 模板的参数

Css div 模板

c++ - Cocos2d-x 3.2 EventListener 在子 Sprite 中不起作用

c++ - 接受一个或两个参数的模板函数

c++ - 算术运算和编译器优化

c++ - 将vec3与模型矩阵相乘的问题(缩放问题)

c++ - 使用类对象填充 3D vector

json - 在 parse.com 类中存储嵌套的 Json