gpt4 book ai didi

c++ - g++ "calling"一个没有括号的函数(不是 f() 而是 f; )。为什么总是返回 1?

转载 作者:IT老高 更新时间:2023-10-28 21:45:30 25 4
gpt4 key购买 nike

在 c++ (GNU GCC g++) 中,我的代码是“调用”一个没有 () 的函数。该函数不工作,但编译正常。

更令人惊讶的是,代码总是返回 1...

有什么解释吗?

我希望函数名只是一个常规指针,但似乎有点不同......

我得到全 1 只是偶然吗?

#include <iostream>
using namespace std;

void pr ()
{
cout << "sth";
}

int main()
{

pr;
cout << pr; // output: 1
cout << *pr; // output: 1
cout << &pr; // output: 1

}

最佳答案

你实际上并没有调用 pr在您的代码中,您将函数指针传递给 cout . pr然后被转换为 bool当被传递给 cout .如果你把 cout << boolalpha事先你会输出 true而不是 1 .

编辑:
使用 C++11,您可以编写以下重载:

    template <class RType, class ... ArgTypes>
std::ostream & operator<<(std::ostream & s, RType(*func)(ArgTypes...))
{
return s << "(func_ptr=" << (void*)func << ")(num_args="
<< sizeof...(ArgTypes) << ")";
}

表示调用cout << pr将打印 (func_ptr=<address of pr>)(num_args=0) .显然,函数本身可以做任何你想做的事情,这只是为了证明使用 C++11 的可变参数模板,你可以匹配任意数量的函数指针。如果没有指定您想要的重载(通常通过强制转换),这仍然不适用于重载函数和函数模板。

关于c++ - g++ "calling"一个没有括号的函数(不是 f() 而是 f; )。为什么总是返回 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17073066/

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