【发布时间】:2010-03-22 07:00:06
【问题描述】:
如何使用声明为
的函数参数void f(double)
{
/**/
}
可以吗?
【问题讨论】:
-
否。只需添加一个不会破坏先前声明的名称
如何使用声明为
的函数参数void f(double)
{
/**/
}
可以吗?
【问题讨论】:
希望一个例子能提供一些帮助:
// Declaration, saying there is a function f accepting a double.
void f(double);
// Declaration, saying there is a function g accepting a double.
void g(double);
// ... possibly other code making use of g() ...
// Implementation using the parameter - this is the "normal" way to use it. In
// the function the parameter is used and thus must be given a name to be able
// to reference it. This is still the same function g(double) that was declared
// above. The name of the variable is not part of the function signature.
void g(double d)
{
// This call is possible, thanks to the declaration above, even though
// the function definition is further down.
f(d);
}
// Function having the f(double) signature, which does not make use of
// its parameter. If the parameter had a name, it would give an
// "unused variable" compiler warning.
void f(double)
{
cout << "Not implemented yet.\n";
}
【讨论】:
没有。你必须给它一个名字。 IE。
void f(double myDouble)
{
printf("%f", myDouble * 2);
}
或者如果您使用 iostreams:
void f(double myDouble)
{
cout << myDouble * 2;
}
【讨论】:
varargs.h 以及可变参数语法和支持。
%f 或%g 打印双精度。
这是一个很好的link
void bar(int arg1, int /* Now unnamed */, int arg3)
{
// code for bar, using arg1 and arg3
}
但有时,上述方法不仅用于支持遗留代码,还用于确保选择重载函数,可能是构造函数。换句话说,传递一个额外的参数只是为了确保某个函数被选中。同样,在代码开发过程中,使用未命名参数可能会有所帮助,例如,如果您为某些例程编写存根。
如果可能的话,应该认为应该从函数和所有调用点中完全删除未使用的参数,除非您特别尝试重载 operator new 或类似的东西。
【讨论】:
参数可能仍会被放入堆栈中,因此您可以在那里找到它(参见下面的 cmets)
仅用于示例(非常不便携)
#include<stdio.h>
void f(double)
{
double dummy;
printf("%lf\n",*(&dummy-2)); //offset of -2 works for *my* compiler
}
int main()
{
f(3.0);
}
我不知道你为什么要这样做
【讨论】:
编译器默认会传递 0....这是我们用来区分后缀增量运算符的方式,我们永远不必使用传递的实际值..
【讨论】:
operator++ 或 operator-- 的边缘情况是设计中的一个不幸缺陷,现在已经确定,但它与所有其他未命名或默认参数的行为方式无关。