c++ - 构造函数重载选择 cast operator 而不是 struct type

标签 c++ casting constructor

我遇到了一种奇怪的情况,编译器选择转换结构,即使有一个非常好的构造函数接收结构类型。
一个小例子:

struct A
{
    operator int() {return 1;}
};

struct B
{
    B(A& a) { OutputDebugStringA("A constructor\n"); }
    B(int i) { OutputDebugStringA("int constructor\n"); }
};
A test () { A a; return a;};

int _tmain(int argc, _TCHAR* argv[])
{
    B b(test());
   return 0;
}

解释:A 有一个转换为 int 的运算符。 B2 个重载构造函数,一个接受A 引用,一个接受int
函数 test() 返回一个 A 对象。

出于某种原因,编译器决定将返回值转换为 int,并使用接受 int 的构造函数。 int 构造函数

谁能解释为什么会这样?我有一些理论,但我想要一个基于真实事物的答案(可能是标准的引述)。

注意:
我可以通过将构造函数签名更改为:B(const A& a)B(A&& a)

来获得预期结果(接受类型的构造函数)

最佳答案

您的构造函数采用对 A 的非常量引用,它不能绑定(bind)到临时对象。你在这里临时传递它:

 B b(test());
 //  ^^^^^^ temporary A

所以唯一有效的构造函数是采用int 的构造函数。您可以通过使相关构造函数采用 const 引用来更改此行为:

B(const A& a) { OutputDebugStringA("A constructor\n"); }
//^^^^^

对于 C++11 中的 B(A&& a); 也是如此。

或者,保留原始构造函数签名并传递左值也会导致构造函数调用:

A a;
B b(a);

关于c++ - 构造函数重载选择 cast operator 而不是 struct type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17843139/

相关文章:

c++ - 测试我正在编写的程序

c++ - CRTP 和方法返回 void *

java - 将 List<SubClass> 转换为 List<BaseClass> 的最有效方法

C++ 构造函数 : garbage while initialization of const reference

c++ - std::variant of template specializations 转换 move 构造函数

c++ - 合并排序与 pthreads 在 c++ 中不起作用

c++ - 与 boost::condition_variable 的线程同步

C++ 避免构造对象

c - 将返回对象指针的函数强制转换为返回空指针的函数是否合法?

java - 从字符串构建 List<T>