gpt4 book ai didi

c++ - 为什么只有指向函数的指针而不是函数的var?

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

在C/C++中,我们可以声明/定义一个类型的函数指针,然后声明/定义一些该类型的变量。但我认为这是模棱两可的。

例如:

typedef void ( *pFunc )();
// typedef void ( aFunc )();
void theFunc() {
cout << "theFunc has been called successfully." << endl;
};

int main() {
pFunc pf0 = theFunc;
pFunc pf1 = &theFunc;

pf0();
( *pf0 )();
pf1();
( *pf1 )();
};

理论上只有pFunc pf1 = &theFunc;(*pf1)();是合法的,但以上都可以通过编译。

Pascal syntax ,我们需要分别定义函数的变量或函数指针的变量,它们的含义是不同的,而且更清晰(至少我是这么认为的)!

此外,我们不能声明/定义函数的 var 而不是函数指针的 var!我尝试了以下操作但失败了。

typedef void ( aFunc )();
aFunc af0 = theFunc;

如果是int/double等其他类型,则有非常严格的语法限制我们正确使用它们。 (如果int*int不同,为什么*pf0pf0相同? !)

那么,我可以认为这是 C/C++ 标准的错误吗?

最佳答案

一些声明的类型:

// decltype of theFunc is void ()
// decltype of &theFunc is void (*) ()
// decltype of *theFunc is void (&) ()

现在,关于您的代码,由于函数可以隐式转换为指向该函数的指针,我们有:

using pFunc = void(*)();
using rFunc = void(&)();

pFunc p_fct = &theFunc; // no conversion
pFunc p_fct = theFunc; // conversion lvalue to pointer
pFunc p_fct = *theFunc; // conversion lvalue reference to pointer

rFunc r_fct = *theFunc; // no conversion
rFunc r_fct = theFunc; // conversion lvalue to lvalue reference
rFunc r_fct = &theFunc; // ERROR: conversion pointer to lvalue reference not allowed

到目前为止的转化。现在,pFuncrFunc 类型的任何对象都是可调用对象。另外,请注意 (*p_fct)(*r_fct) 都是 rFunc 类型。因此,您可以按照问题中的描述调用您的函数:

p_fct();    // callable object of type pFunc
r_fct(); // callable object of type rFunc
(*p_fct)(); // callable object of type rFunc
(*r_fct)(); // callable object of type rFunc

请注意,以下内容等同于上述内容:

using Func = void ();
Func* p_fct = &theFunc; // no conversion
Func& r_fct = *theFunc; // no conversion
p_fct(); // callable of type Func* or pFunc
r_fct(); // callablel of type Func& or rFunc

编辑 从以下评论回答问题:“为什么他们以这种方式排列”:函数无法复制(如@JohnBurger 的回答中所述)。这就是为什么您的代码:

typedef void ( aFunc )();
aFunc af0 = theFunc;

没用。如上所述,您可以执行以下操作:

typedef void ( aFunc )();
aFunc* af0 = &theFunc; // or theFunc, or even *theFunc

或者你可以这样做:

auto myFct = theFunc;

但是请记住,myFctdecltype 仍然是void (*)()

关于c++ - 为什么只有指向函数的指针而不是函数的var?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57354637/

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