c++ - 非常量复制构造函数和返回值的隐式转换

标签 c++ gcc copy-constructor implicit-conversion

考虑以下 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/

相关文章:

c++ - 如何使用 GLSL 在体积渲染中进行混合?

c++ - g++ 不会在模板代码中发出 -Wsign-compare

c - 使用 GCC 交叉编译器时对 printf 的 undefined reference

c++在复制构造函数中使用const?

c++ - 如果可能,移动插入的容器元素

c++ - 打包虚幻引擎代码插件时出错 : Remote compiling requires a server name?

c++ - "Undefined reference to"链接目标文件时出错

C++ 不同的错误使用不同的 gcc 优化

C++03:使用模板构造函数时保留默认复制构造函数

c++ - 使用指针复制构造函数