【问题标题】:No Function to Pointer Decay during Assignment分配期间没有指针衰减的功能
【发布时间】:2022-01-05 08:22:40
【问题描述】:

在下面给出的代码sn-p中,当我写f = A;时,为什么A不衰减指向一个函数的指针?

//Func is alias for "pointer to a function that returns an int and does not take any parameter"
typedef int (*Func)();

int A(){
    return 1;
}
int main()
{
    Func* f = &A;//cannot convert ‘int (*)()’ to ‘int (**)()’ in initialization - I UNDERSTAND THIS ERROR
   
   
    f = A;//error: cannot convert ‘int()’ to ‘int (**)()’ in assignment - My QUESTION IS THAT IN THIS CASE WHY DOESN'T "A" decay to a pointer to a function and give the same error as the above 
    
}

我知道为什么Func *f = &A; 会产生错误。但我预计f = A; 会产生相同的错误,因为我认为在这种情况下A 将衰减为指向函数的指针,因此应该产生与Func*f = &A; 相同的错误。准确地说,我以为我会得到错误

error: cannot convert ‘int(*)()’ to ‘int (**)()’ in assignment

但令我惊讶的是,没有衰减,我没有收到上述错误。

为什么/怎么会这样?也就是为什么没有衰变。

【问题讨论】:

  • 知道了。误读了问题。

标签: c++ function c++11 function-pointers


【解决方案1】:

为什么 A 不衰减为指向函数的指针?

错误消息说函数 (int()) 不能隐式转换为指向函数指针 (int (**)()) 的指针,因为表达式 (A) 的类型是函数。

如果存在通过衰减类型到目标类型的有效转换序列,则函数将衰减。但是没有这样的转换序列,所以程序是病态的。

【讨论】:

  • 好的,您能否从标准中指出,“只有在存在有效的转换序列时才会发生指针衰减函数”。我想知道(在哪些情况下)何时允许衰减。
  • 所以这意味着,因为即使有衰减,rhs 和 lhs 上的类型也会不匹配,所以这是行不通的。我的理解正确吗?
  • @AanchalSharma 一般来说,根本不会有无缘无故发生的转换。标准并没有说函数名会被转换,而是函数名可以被隐式转换。
  • 那么这样说是否正确,"即使有衰减也没关系,因为左侧的类型和右侧的衰减类型仍然会不匹配。” 因此,编译器给出了无法将 int() 转换为 int(**)() 的错误。
猜你喜欢
  • 1970-01-01
  • 2017-05-05
  • 2011-11-14
  • 1970-01-01
  • 1970-01-01
  • 2021-05-06
  • 1970-01-01
  • 2012-11-14
  • 2021-12-01
相关资源
最近更新 更多