问题描述
为什么下面的代码没有显示对重载函数的未定义调用"错误?仅仅是因为int是内置类型?在标准中的哪里可以找到转换为内置类型的保证,例如在下面的代码中?...谢谢!
why do we not see a "undefined call to overloaded function" error with the code bellow? just because int is a built in type? where in the standard can I find the guarantee for the conversion to built in type, such as in the code bellow?... thanks!
#include <iostream>
using namespace std;
class B {
public:
operator int(){ return 0; }
};
class A {
public:
A( int i ) { };
};
void f ( int i ) { cout << "overload f(int) was used!";};
void f ( A a ) { cout << "overload f(A) was used!" ;};
int main () {
B b;
f( b );
}
推荐答案
与内置类型无关.您为B
定义了operator int
.这意味着您提供了从B
到int
的用户定义的转换.根据标准的12.3.4,最多将一个用户定义的转换(构造函数或转换函数)隐式应用于单个值".这就是为什么不将其转换为A
的原因,因为这将需要两次隐式转换.
It has nothing to do with being a built-in type. You defined operator int
for B
. This means that you have provided a user-defined conversion from B
to int
. According to 12.3.4 of the standard, "at most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value." This is why it is not converted to A
, because that would require two implicit conversions.
确切确定何时发生这种情况的规则有些复杂,因此许多人建议您避免提供用户定义的转换.定义它们的另一种方法是为构造函数提供一个参数.您可以在开头添加explicit
,以避免将其隐式应用.
The rules for determining exactly when this happens are somewhat complicated, so many people advise that you avoid providing user-defined conversions. Another way of defining these is to provide a constructor with one argument; you can add explicit
to the beginning to avoid it being applied implicitly.
当您调用f(b)
时,编译器将应用您提供的将b
转换为int
的转换.如果要将其转换为A
,则必须定义从B
到A
的转换,或显式应用其中的一种转换,例如f(int(b))
或f(A(b))
.
When you call f(b)
, the compiler applies the conversion that you provided to convert b
to int
. If you want to convert it to A
, you'll have to define a conversion from B
to A
, or apply one of the conversions explicitly, like f(int(b))
or f(A(b))
.
这篇关于函数重载和类型转换解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!