作者freesamael (烧卖)
站内Programming
标题Re: [问题]Dev C++当中pow函数的使用
时间Sun Nov 11 03:17:05 2007
※ 引述《[email protected] (延宕的人生)》之铭言:
: pow(2,3); 不接受,因为都是整数,没有pow(int, int),可以理解
: pow((float)2,3.0); 不接受,因为没有pow(float, double)的定义
: pow(2,3.0) 但是这个却接受,不过并没有pow(int, double)的定义啊?
Function overload 的时候,c++ compiler 透过称作 overload resolution 的机制
挑选出 best viable function。作法是比较所有 overloaded functions 的每一个
参数转换的 rank,细节有点复杂,简单来说经过越简单的转换 rank 越好。
对 standard conversion 的部份而言,rank 是
exact match > promotion > conversion
现在的 pow 有六个 overloaded functions:
pow(double, double)
pow(double, int)
pow(float, float)
pow(float, int)
pow(long double, long double)
pow(long double, int)
以下分别分析三种情况的转换。
====== pow(int, int) ======
以第一种情况来看,对这六个 function 的参数一的转换都是
floating-integral conversion (意指从浮点数转换成整数,或是从整数转换成浮点数)
因此 rank 相同。
但是看参数二的转换,第一、三、五个是 floating-integral conversion,但是
第二、四、六个都是 identity conversion (意即不用转换),後者 rank 较高。
最後剩下三个选择:
pow(double, int)
pow(float, int)
pow(long double, int)
由於这三者的每个参数转换 rank 都一样,因此无法比较优劣,compiler 会吐出
一个"ambiguous" (模棱两可的) 的错误讯息,因为它不知道该选谁。
====== pow(float, double) ======
同样六个 function,对 pow(float, double) 的第一个参数转换分别为
floating point promotion (专指 float 转 double)
floating point promotion
identity
identity
floating point conversion (浮点数之间的转换)
floating point conversion
因此 3、4 > 1、2 > 5、6
第二个参数则分别为
identity
floating-integral conversion
floating point conversion
floating-integral conversion
floating point conversion
floating-integral conversion
因此 1 > 3、4、5、6
根据 ISO Standard,这样子还是 ambiguous,选不出最好的一个。
就拿 pow(float, float) 和 pow(double, double) 来说好了,前者的参数一 rank 比
後者高,但後者的参数二 rank 比前者高,这样就是 ambiguous,无法比较谁比较好。
====== pow(int, double) ======
针对第三种情况,六者的参数一转换都是 floating-integral conversion,
参数二转换则分别是:
exact match
floating-integral conversion
floating point conversion
floating-integral conversion
floating point conversion
floating-integral conversion
因此 1 > 3、4、5、6,compiler 很高兴的宣布 best viable function 就是
pow(double, double),於是编译过了。
我知道看起来有点难懂,因为细节还满罗唆的,但我又不想写太长...
--
Licensed under CC2.5(TW) by-sa, Samael Wang.
http://creativecommons.org/licenses/by-sa/2.5/tw/
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 220.135.82.153
※ 编辑: freesamael 来自: 220.135.82.153 (11/11 03:20)
1F:推 ledia:你写得很清楚呀 140.112.30.56 11/11 03:28
2F:推 gpmm:推推!好文! 61.57.130.248 11/11 08:07
3F:推 sunneo:GJ 讲的很细了220.132.228.138 11/12 00:26
4F:→ freesamael:S大夸奖我耶~ 这样我会骄傲 >/////< 220.135.82.153 11/12 00:36
5F:推 chchwy:推! 203.68.15.109 11/13 01:21