Asa*_*oor -3 c++ methods const function overload-resolution
void print( int & a ){ cout << a << endl; }
void print( const int & a ){ cout << 2*a << endl; }
void print( float a ){ cout << 3*a << endl; }
Run Code Online (Sandbox Code Playgroud)
为什么2输出print(1)?
这个问题的原则是你需要知道匿名临时工不能绑定到非const引用,它们可以绑定到const引用.
1是匿名临时类型int.
因此const int&,重载解析有利于绑定.
有些编译器(较旧的MSVC)会错误地允许绑定int&.在标准C++中,如果const int&缺少float重载,则将调用重载.
| 归档时间: |
|
| 查看次数: |
82 次 |
| 最近记录: |