C++ string and overloaded operators -
i'm studying c++ library type string. looking operation type can perform, among concatenation. know in c++ operators can overloaded suit class types needs,and know character string literals const char arrays under hood. so, know string type defines constructor takes string literal argument , converts string, can initialize string using:
string s="hello!"
what happens here impicit conversion (through constructor takes const char*) string , copy initialization performed (through copy-constructor of string).
so far good.. (correct me if getting wrong far)
now, know can concatenate 2 strings, or can concatenate string , char literal (or vice versa) , string , string literal (so suppose first happens because there's overloaded + operator takes symmetrically char , string, latter happens overloaded + opeartor concatenates 2 strings , implicit conversion const char* string). questions are:
1: why can't concatenate 2 string literals? shouldn't operator+ takes 2 strings called (and 2 implicit conversion performed const char* string) ?
string s="hi"+" there";
2: tried concatenate char literal , string literal (calling operator+ takes char , string) garbage in resulting string, compiler doesn't mind, result not want.
string s='h'+"ello!"; cout<<s<<endl;
i garbage out.if operator+(char,const string&) exists should called after implicitly converting "ello" string shouldn't it?
can please explain?
1) concatenating 2 string literals.
"hello" + " world"
the compiler has no hint should looking related std::string
-- looking @ 2 const char[]
objects, , cannot +
(or const char *
degraded to).
2) using
operator+
on char literal , string literal.
(thanks user dyp pointing in right direction.)
if literally mean char
literal -- e.g. 'a'
-- you're running afoul of 1 of more surprising things c/c++ have offer.
consider: a[i]
equivalent i[a]
. (this fact.)
so, if write:
'a' + "hello"
...that equivalent (in ascii)...
"hello" + 97
...which pointer nowhere, i.e. constructing std::string
undefined behaviour.
Comments
Post a Comment