运算符重载和函数重载产生不明确的编译器错误
operator overloading and function overloading producing ambiguous compiler error
在给定的代码中,我无法理解为什么编译器在调用函数时会产生错误。它是传递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;
}
我无法理解为什么编译器在调用函数时会产生错误
编译器应该如何确定要调用哪个函数?在与名称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
的隐式转换,并且需要显式强制转换,如前所示。
调用fun(t);
不明确,因为fun
的两个重载都有资格使用它。
这又是因为t
是一个可以转换为Test2
和int
的Test
对象。
将任一转换运算符标记为explicit
将解决此问题。
在此处查看演示。
相关文章:
- 重载方法的方式会在使用临时调用时生成编译器错误
- C++ 编译器错误:P1LinkedList.cpp:145:错误:重载的"to_string(int&)"调用不明确
- 在gcc中意外调用了Const重载.编译器错误或兼容性修复程序
- 编译器无法找到重载
- msvc 编译器(和其他编译器)如何知道要绑定到哪个 std 重载?
- 从 std::ostream 重载 << 运算符时,为什么编译器会给出"too many parameters for this operator function"错误?
- 如何让编译器知道要调用函数的哪个重载以避免歧义?
- 编译器无法推断 std::max 的重载
- 如何让编译器在C++中更喜欢常量方法重载?
- 模板实例化失败:编译器选择不正确的重载函数
- 为什么方法重载或枚举标志定义会触发 gcc7.2 编译器警告?
- 编译器选择错误的重载函数
- 运算符重载关联性编译器优化
- C++方法重写和重载(编译器级别)
- 我重载了一个运算符*()函数来计算两个矩阵的总和,但编译器提示此错误
- 跨编译器的 constexpr 成员函数的重载解析不一致
- 运算符重载和函数重载产生不明确的编译器错误
- MSVC编译器错误将模板与枚举参数重载时
- 强制编译器选择常量运算符重载
- 为什么编译器可以通过引用传递和值传递来重载函数