C ++操作符重载 - 从类转换 [英] C++ Operator overloading - casting from class
问题描述
在将Windows代码移植到Linux时,我遇到了以下GCC 4.2.3错误消息。 (是的,我知道它是一个微小的老版本,但我不能轻易升级。)
While porting Windows code to Linux, I encountered the following error message with GCC 4.2.3. (Yes, I'm aware that it's a slight old version, but I can't easily upgrade.)
main.cpp:16: error: call of overloaded ‘list(MyClass&)’ is ambiguous
/usr/include/c++/4.2/bits/stl_list.h:495: note: candidates are: std::list<_Tp, _Alloc>::list(const std::list<_Tp, _Alloc>&) [with _Tp = unsigned char, _Alloc = std::allocator<unsigned char>]
/usr/include/c++/4.2/bits/stl_list.h:484: note: std::list<_Tp, _Alloc>::list(size_t, const _Tp&, const _Alloc&) [with _Tp = unsigned char, _Alloc = std::allocator<unsigned char>]
我使用以下代码来生成此错误。
I'm using the following code to generate this error.
#include <list>
class MyClass
{
public:
MyClass(){}
operator std::list<unsigned char>() const { std::list<unsigned char> a; return a; }
operator unsigned char() const { unsigned char a; return a; }
};
int main()
{
MyClass a;
std::list<unsigned char> b = (std::list<unsigned char>)a;
return 0;
}
有人遇到此错误吗?更重要的是,如何绕过它? (可以通过使用 GetChar()
, GetList()
等函数完全避免重载,但我想避免这种情况。)
Has anyone experienced this error? More importantly, how to get around it? (It's possible to completely avoid the overload, sure, by using functions such as GetChar()
, GetList()
etc, but I'd like to avoid that.)
(顺便说一下,删除 operator unsigned char()
删除错误。)
(By the way, removing "operator unsigned char()
" removes the error.)
推荐答案
如果删除转换,它会正确编译, :: list is being executed。
It compiles properly if you remove the cast, and I've checked that the operator std::list is being executed.
int main()
{
MyClass a;
std::list<unsigned char> b = a;
return 0;
}
或者如果将它强制转换为const引用。
Or if you cast it to a const reference.
int main()
{
MyClass a;
std::list<unsigned char> b = (const std::list<unsigned char>&)a;
return 0;
}
这篇关于C ++操作符重载 - 从类转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!