考虑以下 C++ 代码:
struct B { };
struct A
{
A(int);
A(A&); // missing const is intentional
A(B);
operator B();
};
A f()
{
// return A(1); // compiles fine
return 1; // doesn't compile
}
这在 MSVC++ 2010 上编译得很好(事实上,在 MSVC 上,如果我完全删除 B
,它甚至可以工作)。它不适用于 GCC 4.6.0:
conv.cpp: In function ‘A f()’:
conv.cpp:13:9: error: no matching function for call to ‘A::A(A)’
conv.cpp:13:9: note: candidates are:
conv.cpp:6:2: note: A::A(B)
conv.cpp:6:2: note: no known conversion for argument 1 from ‘A’ to ‘B’
conv.cpp:5:2: note: A::A(A&)
conv.cpp:5:2: note: no known conversion for argument 1 from ‘A’ to ‘A&’
conv.cpp:4:2: note: A::A(int)
conv.cpp:4:2: note: no known conversion for argument 1 from ‘A’ to ‘int’
令我困惑的是消息 no known conversion for argument 1 from ‘A’ to ‘B’
。考虑到 A::operator B()
定义非常明确,这怎么可能是真的?
最佳答案
因为你不能进行不止一次的隐式转换。你将不得不去 A::A(A::A(int)::operator B())
来使它工作,而对于编译器来说,这是太多的步骤来弄清楚它是拥有。
关于c++ - 非常量复制构造函数和返回值的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6401818/