The declarations are just regular C declarations of functions, types (including other classes), or data.
The class binds them together. Each function declaration in the class needs an implementation, which
can be inside the class or (usually) separated out. So the whole thing may look like:
class Fruit { public: peel(); slice(); juice();
private: int weight, calories_per_oz;
};
// an instance of the class
Fruit melon;
Remember, C++ comments start with // and go to the line end.
The implementation of a member function, when placed outside its class, has some special syntactic sugar on the front.
The syntactic sugar :: says "Hey! I'm important! I refer to something in a class."
So instead of looking like the regular C function declaration,
return-type functionname(parameters) {...};
member functions (also known as "methods") will have the form
return-type Classname :: functionname(parameters)
{ . . . };
The :: is called "the scope resolution operators." The identifier that precedes it is a class to look in. If there's no preceding identifier, it means global scope. If the implementation of peel() is put inside the class, it might look like this:
class Fruit { public: void peel(){ printf("in peel"); }
slice();
juice();
private: int weight, calories_per_oz;
};
And, if you separate it out, it will look like this
class Fruit { public: void peel();
slice();
juice();
private: int weight, calories_per_oz;
};
void Fruit::peel(){ printf("in peel"); }
The two approaches are semantically equivalent, but the second is more usual and provides benefits for organizing the source more cleanly using include files. The first approach is commonly used for very short functions, and it makes the code automatically expand in line instead of causing a function
call.
0 comments:
Post a Comment