我有一些像这样的代码
struct B
{
B() {}
B(int v) {}
};
struct A
{
operator int() const { return 1; }
operator B() const { return B(); }
};
int main()
{
A a;
static_cast<B>(a); // Error here
a.operator B(); // This is OK
return 0;
}
它会产生这样的编译错误:
main.cpp: In function ‘int main()’:
main.cpp:16:21: error: call of overloaded ‘B(A&)’ is ambiguous
static_cast<B>(a);
^
main.cpp:4:5: note: candidate: B::B(int)
B(int v) {}
^
main.cpp:1:8: note: candidate: constexpr B::B(const B&)
struct B
^
main.cpp:1:8: note: candidate: constexpr B::B(B&&)
我不要求如何修复这个问题,只是想了解为什么编译器不接受它?在我看来,static_cast<B>(a)
等同于a.operator B()
,但似乎编译器读取方式不同。
更新:
这种行为发生在c++17之前。使用c++17,则此代码将不会产生任何编译错误。
static_cast<B>(a)
可能意味着B(a.operator int())
或a.operator B()
。需要将其翻译为:使用static_cast<B>(a)
语句时,可能会被解释为执行B(a.operator int())
或a.operator B()
操作。 - M.Ma.operator B()
作为static_cast
。 - M.Moperator int
设为explicit
可以解决这个问题,并且可能是个好主意。g ++ 表示在 C++17 中可以使用此方法。 - Ry--std=c++1z
与此处提供的背景有关,即GCC对于担保复制省略的看法。 - StoryTeller - Unslander MonicaB b = static_cast<B>(a);
是有歧义的,而B b = a;
却没问题。 - Killzone Kid