gpt4 book ai didi

c++ - C++中的函数指针歧义

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:06:41 26 4
gpt4 key购买 nike

我有两个问题:

Q1) 函数名本身是指针吗??

如果它们是指针,那么它们存储的是什么值?

否则如果它们不是指针,那么,它们是什么以及其中存储了哪些值?

如果我们认为函数名是指针。然后:

void display(){...}

int main ()
{
void (*p)();

**p=display; //Works (justified**, because we are assigning one pointer into another)

**p=&display; //Works (Not justified** If function name is a pointer (let say type*) , then &display is of datatype : type**. Then how can we assign type** (i.e. &display) into type * (i.e. p)??)

**p=*display; //Works (Not justified** If function name is a pointer ( type *) ,then, how can we assign type (i.e. *display) into type * (i.e. p) ?? )
}

再次,

cout<<display<<";"<<&display<<";"<<*display;

打印类似的东西:

0x1234;0x1234;0x1234

[1234只是举例]

[天哪!这怎么可能?指针的地址、它指向的地址和指向地址的值怎么可能都相同?]

Q2) 用户定义的函数指针中存储了什么值?

考虑这个例子:

void display(){...}

int main()
{
void (*f)();

f=display;

f=*f; // Why does it work?? How can we assign type (i.e. *f ) into type * (i.e. f).

cout<<f<<";"<<&f<<";"<<*f;

//Prints something like :

0x1234;0x6789;0x1234
}

[前两个输出是合理的...但是指针(它指向的地址)中的值如何等于指向地址中存储的值?]

再次:

f=*********f; // How can this work?

我在网上搜索过,但所有可用的信息都是关于用法和创建函数指针的示例代码。它们都没有说明它们是什么或它们与普通指针有何不同。

所以我一定遗漏了一些非常基本的东西。请指出我所缺少的。 (抱歉我是初学者的无知。)

最佳答案

函数名称本身是指针吗?

没有。但是,在某些情况下,函数可以自动转换为指向函数的指针。该标准在第 4.3 段中说:

An lvalue of function type T can be converted to a prvalue of type “pointer to T.” The result is a pointer to the function.

(函数名指定一个左值,但可以有其他函数类型的左值)。

在你的例子中

p = display;
p = *p;

就是有这种自动转换。 display*p是函数类型的左值,在需要时,它们会自动自动转换为指向函数的指针类型。

p = *display; 

此处转换发生两次:第一次display转换为 * 的指针运算符,然后它被取消引用,然后再次转换为 = 的指针运营商。

cout << display << ";" << &display << ";" << *display;

在这里,display转换为 operator << 的指针; &display已经是一个指针,因为 &是一个正常的地址获取运算符(operator);和 *display转换为 operator << 的指针在里面display转换为 operator * 的指针.

f = *********f;

这个表达式中有很多这样的转换。自己数一数!

关于c++ - C++中的函数指针歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41577136/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com