The best way I've found to understand operators is always to first learn how to read them out loud.
A summary on how can you read some pointer and class operators (*, &, ., ->, [ ]) that appear in the previous example:
*x can be read: pointed by x
&x can be read: address of x
x.y can be read: member y of object x
(*x).y can be read: member y of object pointed by x
x->y can be read: member y of object pointed by x (equivalent to the previous one)
x[0] can be read: first object pointed by x
x[1] can be read: second object pointed by x
x[n] can be read: (n+1)th object pointed by x
...some code with inline explanations on defining methods outside of the code itself... this always threw me off before.
// example of defining a method outside of the class
// using prototype and scope operator
#include
class CRectangle {
int x, y;
public:
// set_values is a prototype only, defined below
void set_values (int,int);
int area (void) {
return (x*y);
}
};
// set-values defined here using :: scope operator
// notice a, b variables are placed into x, y
// which are private scope with CRectangle class
void CRectangle::set_values (int a, int b) {
x=a;
y=b;
}
int main() {
CRectangle rect;
// set_values is called, passing 3 and 4
rect.set_values (3,4);
// rect.area() sees x,y variables as set_values
// has changed their values per arguments we
// passed to it
cout << "area: " << rect.area();
}
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home