-
Pointer lesson needed
Sorry in advance. I need a pointer class. I'm working on an overload + operator that takes and returns the char in a String at *(s + x) where s is a String and x is an int...so s[x]...
I have it set up as a friend and the following:
Code:
char* operator+(const String& s, int x)
{
return s.m_buf[x];
}
......obviously that's wrong but if I put &s.m_buf[x] wouldn't that double reference?? So bottom line is I don't friggin' know what to put there for a return value and Bjarne Stroupstrup needs to write a book idiots like me can read cause I can't understand a thing he says....LOL!!! Any help or better yet a nice little explaination would be cool.
-
s.m_buf[x] is like *(s.m_buf + x), accessing the character x in s.m_buff
so, following that, &s.m_buf[x] takes the address of x in s.m_buff
since pointers hold the address of an object, it's the Right Thing
-
If you just want to return a char, then just return a char and not a pointer to a char.
Rewrite your return as: char operator + (blah.. blah.. blah..);
else, what you're doing when you apply the ampersand to the variable m_buf is you're returning the address of the current index, x.
And no,that would not be double dereferencing. dereferencing would be: char* ip; *ip = 'v'; dereferencing is applied on pointers. none of the variables in your code are pointers
-
You can treat a reference just as if it was another name, an alias, for the original variable.
Code:
int var = 1, &ref = var;
int *p1 = &var, *p2 = &ref;