2

The example is from Chapter 7 in C++ Primer 5th.

Suppose class Sales_data has such constructor:

Sales_data(const std::string &s): bookNo(s) { }

And it has a public function member:

Sales_data &combine(Sales_data &s){...}

The flowing is error:(item is a Sales_data instance)

item.combine("9-999-9999");

The reason is that: Only One Class-Type Conversion Is Allowed, however, the code mentioned above has two user-defined conversions.

  • "9-999-9999" to string
  • string to Sales_data

Why should literal string convert to string ? Is 9-999-9999 not a string ?

chenzhongpu
  • 6,193
  • 8
  • 41
  • 79

1 Answers1

3

"9-999-9999" is not a string, it is a const char[]. You can fix this by adding a constructor to you class that takes a const char * like:

Sales_data(const char* s): bookNo(s) { };

If you have C++14 support than you could also use a std::string_literal:

item.combine("9-999-9999"s);
NathanOliver
  • 171,901
  • 28
  • 288
  • 402