c – 为什么传递给参数时,我不能隐式地构造一个给定适当构造函数的对象?

在下面的例子中,为什么我不能简单地将一个字符串传递给printFoo()?

#include <string>
#include <iostream>

using namespace std;

class Foo {
public:
  Foo(const Foo &foo) : str(foo.str) {}
  Foo(string str) : str(str) {}

  string str;
};

void printFoo(Foo foo) {
  cout << foo.str << endl;
}

int main() {
  Foo foo("qux");
  printFoo(foo); // OK

  printFoo("qix"); // error: no matching function for call to 'printFoo'

  return 0;
}

无论什么原因,我头脑中都会自动确定并使用构造函数来构造一个对象.

为什么我不能这样做,但是我可以将char [n]常量传递给接受std :: string的参数,例如?

将涉及两个隐含的转换:

> to std :: string
>到Foo

C最多只有一个:

从4个标准转换(N3337)

Standard conversions are implicit conversions with built-in meaning.
Clause 4 enumerates the full set of such conversions. A standard
conversion sequence is a sequence of standard conversions in the
following order:

— Zero or one conversion from the following set:
lvalue-to-rvalue conversion, array-to-pointer conversion, and
function-to-pointer conversion.

— Zero or one conversion from the
following set: integral promotions, floating point promotion, integral
conversions, floating point conversions, floating-integral
conversions, pointer conversions, pointer to member conversions, and
boolean conversions.

— Zero or one qualification conversion.

12.3转换(N3337)

1 Type conversions of class objects can be specified by constructors and
by conversion functions. These conversions are called user-defined
conversions and are used for implicit type conversions (Clause 4), for
initialization (8.5), and for explicit type conversions (5.4, 5.2.9).

2 User-defined conversions are applied only where they are unambiguous
(10.2, 12.3.2). Conversions obey the access control rules (Clause 11).
Access control is applied after ambiguity resolution (3.4).

[…]

4 At most one user-defined
conversion (constructor or conversion function) is implicitly applied
to a single value.

(重点是我)

相关文章
相关标签/搜索