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