c++ - 为什么函数参数调用带有参数的构造函数?

标签 c++

我有这段代码(从 cplusplus.com 偷来的):

// explicit:
#include <iostream>
using namespace std;

class A {};

class B {
public:
  explicit B (const A& x) {}
  B& operator= (const A& x) {return *this;}
  operator A() {return A();}
};

void fn (B x) {}

int main ()
{
  A foo;
  B bar (foo);
  bar = foo;
  foo = bar;

//  fn (foo);  // not allowed for explicit ctor.
  fn (bar);  

  return 0;
}

显然语句 fn (foo); 会调用类 B 中定义的构造函数,我真的不明白为什么。为什么会调用带有参数的构造函数,我的意思是,在不使用引用时,不是简单地复制到函数参数吗?如果 fn (foo); 调用构造函数 B (const A& x) {}fn (bar); 不应生成错误因为没有为类型 B 的参数定义构造函数,例如 B (const B& x) {}?

最佳答案

都是因为fn()的签名:

void fn (B x) {}

fn 只接受类型 B 的对象,并按值传递它们。
那么当使用 A 类型的对象调用 fn() 时会发生什么?

 A foo;
 fn (foo);  // not allowed for explicit ctor.

编译器会尝试找到最匹配的函数 - 一个名为 fn 并接收类型 A 的函数。( Overload resolution )
因为没有这样的函数,它会尝试通过将对象转换为 fn() 接受的类型来找到下一个最佳匹配。
转换构造函数通常会完成这项工作:B (const A& x) {}
但是因为它标有 explicit说明符编译器不能隐式地做。

您必须显式转换对象以便编译器找到匹配项:

fn ((B)foo);  // Explicit conversion is allowed.

关于c++ - 为什么函数参数调用带有参数的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44411731/

相关文章:

c++ - AVX2 收集加载两个整数的结构

c++ - 模板特化不明确

c++ - 将 1 到 100 之间的数字相加 OpenMP

c++ - 链表类

c++ - 如何删除 "Ctrl + Backspace"特殊字符?

c++ - Qt 在构建移动到线程的 QObject 时将 "this"作为父级传递

c++ - 如何在 gtest 中测试 setter 方法?

c++ - 如何在 C++ 中跟踪内存分配(尤其是新建/删除)

c++ - C/C++ 中的显式类型转换运算符

c++ - Mandelbrot 集不会使用 pthread 加速