Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/symfony/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用类定义之外的默认参数定义的默认构造函数,为什么这样做?涉及模板时会发生什么?_C++_Class_Templates_Default Value_Default Constructor - Fatal编程技术网

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

C++ 使用类定义之外的默认参数定义的默认构造函数,为什么这样做?涉及模板时会发生什么?,c++,class,templates,default-value,default-constructor,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.igno

我知道这是一种不好的形式,应该在声明中指定默认值,但如果您愿意,请允许我说几句。。为什么要编译?到底发生了什么

#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;
}
#包括
使用名称空间std;
课堂测试
{
公众:
测试(int n);
};
测试:测试(int n=666)
{

CUT< P>看起来C++规范特别允许第一种情况,不允许第二种!

引用C++规范(第8章3.6/4):

对于非模板函数,可以在同一范围内函数的后续声明中添加默认参数


因此,对于非模板函数,您以后确实可以引入默认参数。不过,不知道为什么这对模板不起作用!

第一种情况是标准允许的;我记得@Johannes曾问过这个问题,而@Nawaz回答过这个问题。(编辑:这是相关的)

不允许使用
模板
版本的原因是
模板
函数仅在显式实例化时才被调用。在您的例子中,编译器将声明视为

test<int> t;
测试t;

->强>编辑< /强>:它可能不同于编译器到编译器。在GCC中。感谢C++规范引用!更多默认参数乐趣:虽然我没有接受你的答案,但我发现它是有信息的,谢谢。

test<int> t;