Prev: value_type of an output iterator
Next: Compiling C++ Templates as opposed to Preprocessing them.
From: Nick Hounsome on 30 Jul 2010 23:32 On Jul 31, 2:15 am, Alexandre Bacquart <tek...(a)free.DELETEME.fr> wrote: > Because there is no implicit conversion from const char* to std::string > in the first argument of the expression. You can resolve it this way: > > const std::string message = string("Hello") + ", world" + exclam; Actually there is an implicit conversion to std::string but the compiler sees no reason to use it in the original line. As it happens there is an operator+(const string&,const char*) but operator+(const string&,const string&) would also work because ",world" WOULD be converted to string. One way to look at it is that at least one of the arguments needs to be a class because operator+ is "defined" for all non-class types provided that we take "defined" to include "defined to be invalid", and this "defined" operator will therefore be preferred to any user supplied one because it doesn't require any conversions. -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
From: Bo Persson on 31 Jul 2010 23:28 Alexandre Bacquart wrote: > On 07/30/2010 10:18 PM, efoss(a)fhcrc.org wrote: >> I'm working through some exercises trying to learn C++. I hung up >> on this one: >> >> This is OK: >> >> const std::string hello = "Hello"; >> const std::string = message = hello + ", world" + "!"; > > Well, no it is not. Remove the first =. But I get it. > >> std::cout<< message<< std::endl; >> >> This is not OK: >> >> const std::string exclam = "!"; >> const std::string = message = "Hello" + ", world" + exclam; >> std::cout<< message<< std::endl; >> >> Why is the second thing not OK? > > Because there is no implicit conversion from const char* to > std::string in the first argument of the expression. You can > resolve it this way: > const std::string message = string("Hello") + ", world" + exclam; > > As long as the first in the expression is a std::string, it works, > the rest can be anything that std::string can concatenate with > operator+. And in this particular case, you could also do the somewhat obvious: const std::string message = "Hello, world" + exclam; or "abuse" the preprocessor to concatenate two adjacent string literals, by just removing the first + const std::string message = "Hello" ", world" + exclam; There just isn't much need for an operator to add two string literals together. Bo Persson -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
First
|
Prev
|
Pages: 1 2 Prev: value_type of an output iterator Next: Compiling C++ Templates as opposed to Preprocessing them. |