C++ 是否可以将一个函数名等同于另一个函数名?
我不确定以下是否可行。有人能给这个要求一个等价物吗C++ 是否可以将一个函数名等同于另一个函数名?,c++,C++,我不确定以下是否可行。有人能给这个要求一个等价物吗 if(dimension==2) function = function2D(); else if(dimension==3) function = function3D(); for(....) { function(); } 您可以使用函数指针 有一种方法,但基本上你要做的是这样声明: void (*foo)(int); void my_int_func(int x) { printf( "%d\n", x );
if(dimension==2)
function = function2D();
else if(dimension==3)
function = function3D();
for(....) {
function();
}
您可以使用函数指针 有一种方法,但基本上你要做的是这样声明:
void (*foo)(int);
void my_int_func(int x)
{
printf( "%d\n", x );
}
int main()
{
void (*foo)(int);
foo = &my_int_func;
/* call my_int_func (note that you do not need to write (*foo)(2) ) */
foo( 2 );
/* but if you want to, you may */
(*foo)( 2 );
return 0;
}
其中函数有一个整数参数
然后你这样称呼它:
void (*foo)(int);
void my_int_func(int x)
{
printf( "%d\n", x );
}
int main()
{
void (*foo)(int);
foo = &my_int_func;
/* call my_int_func (note that you do not need to write (*foo)(2) ) */
foo( 2 );
/* but if you want to, you may */
(*foo)( 2 );
return 0;
}
因此,只要函数具有相同数量和类型的参数,您就应该能够执行所需的操作。假设有两种情况,这是可能的:
function2D()
和function3D()
具有相同的签名和返回类型function
是一个函数指针,其返回类型和参数与function2D
和function3D
相同int function2D()
{
// ...
}
int function3D()
{
// ...
}
int main()
{
int (*function)(); // Declaration of a pointer named 'function', which is a function pointer. The pointer points to a function returning an 'int' and takes no parameters.
// ...
if(dimension==2)
function = function2D; // note no parens here. We want the address of the function -- not to call the function
else if(dimension==3)
function = function3D;
for (...)
{
function();
}
}
<> P>因为这也是标记C++,如果你可以访问<代码> C++ 11 ,或者<代码> STD::Tr1::函数< < /代码>,如果你的编译器支持C++ 98和03,Tr1./P>>,你可以使用<代码> STD::函数< /C>
int function2d();
int function3D();
int main() {
std::function<int (void)> f; // replace this with the signature you require.
if (dimension == 2)
f = function2D;
else if (dimension == 3)
f = function3D;
int result = f(); // Call the function.
}
int function2d();
int function3D();
int main(){
std::function f;//将其替换为所需的签名。
如果(维度==2)
f=函数2d;
否则如果(维度==3)
f=函数3D;
int result=f();//调用函数。
}
正如其他答案中所提到的,确保您的函数具有相同的签名,并且所有函数都将正常工作
如果您的编译器不提供std::function
或std::tr1::function
,那么自从您选择C之后,.++
下面是C++11中的示例
#include <functional>
#include <iostream>
int function2D( void )
{
// ...
}
int function3D( void )
{
// ...
}
int main()
{
std::function<int(void)> fun = function2D;
fun();
}
#包括
#包括
int function2D(void)
{
// ...
}
int function3D(无效)
{
// ...
}
int main()
{
std::function fun=function2D;
乐趣();
}
<代码> C还是C++?您需要的是一个函数指针“我知道下面是不可能的。”-是的。@H2CO3:酷。我不知道!谢谢通知……:)把它和跳转表联系起来,投了大票。精彩的解释。@H2CO3:谢谢。:)太糟糕了,我被封了。是的,<代码> STD::函数< /> >可能是C++中使用的正确的东西。