函数重载和函数指针 [英] Function overloading and function pointers

查看:144
本文介绍了函数重载和函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数的名称是指向函数的指针...

但是在函数重载的情况下,两个函数的名称是相同的...

函数的名字指向?

解决方案

否则它是模糊的。请参见此示例(以下修改除外):

  void foo(int a){} 
void foo(int a,char b){}

int main $ b {
void(* functionPointer1)(int);
void(* functionPointer2)(int,char);
functionPointer1 = foo; //获取foo(int)的地址
functionPointer2 = foo; //获取地址foo(int,char)
}



否则会破坏类型安全性和

(可能出现调用约定,您不注意的随机更改等问题。)


The name of a function is a pointer to the function...
But in case of function overloading the names of two functions are the same...
So which function does the name point to?

解决方案

It depends on the context; otherwise it's ambiguous. See this example (modified except below):

void foo(int a) { }
void foo(int a, char b) { }

int main()
{
    void (*functionPointer1)(int);
    void (*functionPointer2)(int, char);
    functionPointer1 = foo; // gets address of foo(int)
    functionPointer2 = foo; // gets address of foo(int, char)
}

You can do this in many ways, but the #1 rule?

Avoid casts!

Otherwise you'll break type safety and probably shoot yourself in the foot either then or later.
(Issues can come up with calling conventions, random changes you don't notice, etc.)

这篇关于函数重载和函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆