【问题标题】:operator overloading and function overloading producing ambiguous compiler error运算符重载和函数重载产生不明确的编译器错误
【发布时间】:2019-03-13 10:39:40
【问题描述】:

在给定的代码中,我无法理解为什么在调用函数时编译器会产生错误。它正在传递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;
}

【问题讨论】:

  • 您正在调用fun(t),其中t 的类型为Testfun() 的唯一重载接受 intTest2。因此,编译器查找Testfun() 重载将接受的其他类型的转换,并找到operator Test2()operator int()。因此,这两个序列“将t转换为Test2并将其传递给接受Test2fun()”和“将t转换为int并将其传递给接受@的fun() 987654341@" 同样有效,编译器没有理由偏爱一个。因此调用fun(t) 被诊断为模棱两可。

标签: c++ class object int operator-overloading


【解决方案1】:

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

编译器应该如何确定调用哪个函数?重载集中有两个函数与名称 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 的隐式转换,并且需要如前所示的显式转换。

【讨论】:

    【解决方案2】:

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

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

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

    在此处查看Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-27
      相关资源
      最近更新 更多