运算符重载和函数重载会产生模糊的编译器错误

问题描述 投票:0回答:2

在给定的代码中,我无法理解为什么编译器在调用函数时会产生错误。它传递的是test类的对象,它的数据成员是test2

class Test2 {
    int y;
};

class Test {
    int x;
    Test2 t2;
public:
    operator Test2 () {return t2;}
    operator int () {return x;}
};

void fun (int x) { 
    cout << "fun(int) called";
}

void fun (Test2 t) {
    cout << "fun(Test 2) called";
}

int main() {
    Test t;
    fun(t);
    return 0;
}
c++ class object int operator-overloading
2个回答
0
投票

我无法理解为什么编译器在调用函数时会产生错误

编译器应该如何确定要调用哪个函数?在与名称func相关联的重载集中有两个函数,以及两个允许隐式转换为同样匹配此重载集的两个函数参数的类型的运算符。

情况与此相同

void f(long);
void f(short);

f(42); // Error: both conversions int -> log and int -> short possible

您可以通过例如修复它

fun(static_cast<Test2>(t)); // be explicit on the calling side

或者将一个(或两个)转换运算符标记为explicit

explicit operator Test2 () {return t2;}

它会禁用对Test2的隐式转换,并需要显式转换,如前所示。


0
投票

调用fun(t);是不明确的,因为fun的重载都符合条件。

这也是因为t是一个Test对象,可以转换为Test2int

将其中一个转换运算符标记为explicit将解决此问题。

在这里查看Demo

© www.soinside.com 2019 - 2024. All rights reserved.