本文介绍了为什么c ++函数的地址始终为True?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会这样

#include <iostream>

using namespace std;

int afunction () {return 0;};

int anotherfunction () {return 0;};

int main ()
{
    cout << &afunction << endl;
}

为此,

1

  1. 为什么每个函数的地址都是正确的?
  2. 如果所有函数共享(看来)相同的地址,那么函数指针又如何工作?

推荐答案

函数地址不是"true".接受任意函数指针的ostream没有重载.但是有一个布尔值,并且函数指针可以隐式转换为bool.因此,编译器会将 afunction 从其实际值转换为 true false .由于您无法在地址 0 处使用函数,因此打印的值始终为 true ,而 cout 会显示为 1 .

The function address isn't "true". There is no overload for an ostream that accepts an arbitrary function pointer. But there is one for a boolean, and function pointers are implicitly convertable to bool. So the compiler converts afunction from whatever its value actually is to true or false. Since you can't have a function at address 0, the value printed is always true, which cout displays as 1.

这说明了为什么通常不赞成隐式转换.如果到 bool 的转换是明确的,那么您将有一个编译错误,而不是默默地做错事.

This illustrates why implicit conversions are usually frowned upon. If the conversion to bool were explicit, you would have had a compile error instead of silently doing the wrong thing.

这篇关于为什么c ++函数的地址始终为True?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 12:34