Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/142.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 重载解析和用户定义的转换_C++_Type Conversion_Overload Resolution - Fatal编程技术网

C++ 重载解析和用户定义的转换

C++ 重载解析和用户定义的转换,c++,type-conversion,overload-resolution,C++,Type Conversion,Overload Resolution,考虑这个例子: struct Foo { Foo(int){cout << "Foo(int)\n";} Foo(double){cout << "Foo(double)\n";} operator int()const{cout << "operator int()\n"; return 0;} operator double()const{cout << "operator double()\n"; retur

考虑这个例子:

struct Foo
{
    Foo(int){cout << "Foo(int)\n";}
    Foo(double){cout << "Foo(double)\n";}

    operator int()const{cout << "operator int()\n"; return 0;}
    operator double()const{cout << "operator double()\n"; return 0.;}
};

void bar(Foo){cout << "bar(Foo)\n";}
void bar(float){cout << "bar(float)\n";}



int main()
{

    int i = 5;
    bar(i); // whey bar(float) and not bar(Foo)?
}
structfoo
{
Foo(int){cout
这是否意味着标准转换优于用户定义转换

是的。标准转换总是优于用户定义的转换。请参阅

在决定最佳匹配时,编译器根据调用中传递的类型与竞争参数列表的匹配方式对评级系统进行操作。按照匹配优度的降序排列:

  • 精确匹配,例如参数为双精度,参数为双精度
  • 晋升
  • 标准类型转换
  • 构造函数或用户定义的类型转换

“我知道我不应该让“转换向量”过载以获取相关类型(这里是算术类型)”ReMyLeBeAu:这是因为只定义了那些相关类型的一个转换,允许在转换为类类型之前进行标准转换。@ ReMyLeBeAu:不应该定义一个或多个转换到算术类型(通过转换来关联类型)。考虑这个例子:<代码> Stutt {a(int=0))。{cout