Pointer to c++ string
in the following code, I am using a pointer to a c++ string in the change() function.
Is there anyway to use the string class' operators when working with a pointer to a string? For example, at() works for the [] operator, but is there any way to use the [] operator?
#include <string>
#include <iostream>
using namespace std;
void change(string * s){
s->开发者_JAVA技巧at(0) = 't';
s->at(1) = 'w';
// s->[2] = 'o'; does not work
// *s[2] = 'o'; does not work
}
int main(int argc,char ** argv){
string s1 = "one";
change(&s1);
cout << s1 << endl;
return 0;
}
Dereference it:
(*myString)[4]
But, may I suggest instead of a pointer, using a reference:
void change(string &_myString){
//stuff
}
That way you can use everything like you would with the object.
you're running into an operator precedence issue, try
(*s)[0]
Another solution, for completeness' sake:
s->operator[](2) = 'o';
First and foremost, no reason to pass a std::string
by pointer here, use a reference. Secondly, I think this could work:
(*s)[i]
But better would be:
void change( string &s )
{
s.at(0) = 't';
s.at(1) = 'w';
s[2] = 'o';
s[2] = 'o';
}
Cuts down on dereferencing as well.
精彩评论