In quasi-standard C + +, the restrictions on the value of the default variable are very vague. Based on this, many compilers allow developers to include default variable values in function declarations, pointers and references to functions, pointers to member functions, and typedef declarations.
Please take a look at the following procedure:
struct A
{
void func(int x=5)
{
}
};
void g(int n=12)
{
}
// 根据C++标准,不能在以下声明中使用缺省变量值。
void (*pf)(inti=120);
void (A::*pmf)(int j=50);
typedef void (*PF)(inti=100);
// 函数的引用
typedef void (&PRF)(inti=100);
int main()
{
pf=g;
PF pf2=g;
pmf=&A::func;
A a;
//这些调用使用了哪些缺省值?
pf();
pf2();
(a.*pmf)();
}
A::func () and G () have the default variable value, which is reasonable. However, the pointer pmf,pf and TYPEDEFPF also define the default variable values. According to the C + + standard, this is not standard.
One of the problems with the actual use of this code is that the default values provided in these declarations are inconsistent with the values provided by the A::func () and g () functions. That is, many compilers use this code as a nonstandard extension. When the G () function is invoked, my compilation will use 120 as the default for PF, but for PF2 it uses 100 as its default value.
As a rule, you should avoid using pointers to functions, pointers to member functions, and the values of default variables named by typedef. Even if your compiler accepts them, it may not be accepted in later versions. Also, the code reduces the dexterity of the program, and it can mislead developers who cannot tell which compiler receives the default variable. In the legitimate code that uses these default value values, the suggestion here is to add some necessary comments to illustrate which default variable values are required.