why*_*sed 6 c++ templates class 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;
}
Run Code Online (Sandbox Code Playgroud)
输出: 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;
}
Run Code Online (Sandbox Code Playgroud)
错误:没有适当的默认构造函数可用
感谢您的时间!
看起来C++规范专门允许第一种情况而不允许第二种情况!
引用 C++ 规范 (§8.3.6/4):
对于非模板函数,可以在同一范围内的函数的后续声明中添加默认参数。
所以看起来对于非模板函数,您确实可以稍后引入默认参数。但不知道为什么这不适用于模板!