默认构造函数用类定义之外的默认参数定义,为什么这样工作?和涉及的模板发生了什么? [英] Default constructor defined with default arguments outside the class definition, why does this work? and what happens with templates involved?
问题描述
我知道这是一个错误的形式,并应在声明中指定默认值,但如果你愿意沉溺我一会儿..为什么这样编译?和正在发生什么?
#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;
}
错误: p>
感谢您的时间!
特别允许第一种情况和不允许第二种情况!
从C ++规范(> 8.3.6 / 4)报价:
对于非模板函数,可以在同一作用域中的函数的后续声明中添加默认参数。
所以它看起来像非模板函数,你可以确实介绍以后的默认参数。不知道为什么这对模板不起作用,虽然!
I am aware this is bad form and that default-values should be specified in the declaration, but if you would please indulge me for a moment.. why does this compile? and what is happening exactly?
#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;
}
Output: 666
.. how do templates affect the same piece of code?
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;
}
Error: no appropriate default constructor available
Thank you for your time!
It looks like the C++ specification specifically allows the first case and disallows the second!
Quote from the C++ spec (§8.3.6/4):
For non-template functions, default arguments can be added in later declarations of a function in the same scope.
So it looks like for non-template functions, you can indeed introduce the default arguments later on. No idea why this doesn't work for templates, though!
这篇关于默认构造函数用类定义之外的默认参数定义,为什么这样工作?和涉及的模板发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!