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


#include <string>
#include <iostream>

using namespace std;

class Foo {
  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



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.


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.