Your second program is malformed. It’s not using std::string::operator[]
at all.
string * ps = new string(str);
ps[0] = 'n';
Not only does std::string
support the []
operator, every pointer to a type also supports the []
operator. It’s how C style arrays work, and it’s what you’re doing in the code above.
ps
isn’t a string
. It’s a pointer. And ps[0]
is the one string, not unlike *ps
.
You probably wanted this instead:
#include <iostream>
#include <string>
using namespace std;
void remodel(string & str){
string * ps = new string(str);
(*ps)[0] = 'n';
// or: ps->operator[](0) = 'n';
cout<<*ps<<endl;
delete ps;
}
int main(){
string str = "Hello world";
remodel(str);
cin.get();
return 0;
}
Or, more idiomatically, use this instead:
#include <iostream>
#include <string>
using namespace std;
void remodel(string & str){
string ps = str;
ps[0] = 'n';
cout<<ps<<endl;
}
int main(){
string str = "Hello world";
remodel(str);
cin.get();
return 0;
}
4
solved Difference between std::string [] operator and at()