C++ Class Member Functions
Class member functions are functions whose definitions and prototypes are written inside the class definition, just like other variables in the class definition. A class member function is a member of the class; it can operate on any object of the class and can access all members in the object.
Let us look at the previously defined class Box. Now we want to use member functions to access the members of the class, instead of directly accessing these class members:
Member functions can be defined inside the class definition, or separately usingScope Resolution Operator ::to define. Member functions defined in the class definition declare the function asInlineinline, even if the inline identifier is not used. So you can definegetVolume()Function:
You can also use it outside the class.Scope Resolution Operator ::Define the function as follows:
Here, one point needs to be emphasized: the class name must be used before the :: operator. Calling a member function is using the dot operator on the object (.), so that it can operate on data related to that object, as follows:
Let us use the concepts mentioned above to set and get the values of the different members in the class:
Example
When the above code is compiled and executed, it produces the following results:
Box1 的体积: 210 Box2 的体积: 1560other extensions