C++ Class Member Functions

C++ Classes & Objects

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:

class Box { public: double length; // Length double breadth; // Width double height; // Height double getVolume(void);// Return volume };

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:

class Box { public: double length; // Length double breadth; // Width double height; // Height double getVolume(void) { return length * breadth * height; } };

You can also use it outside the class.Scope Resolution Operator ::Define the function as follows:

double Box::getVolume(void) { return length * breadth * height; }

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:

Box myBox; // Create an object myBox.getVolume(); // Call the member function of the object

Let us use the concepts mentioned above to set and get the values of the different members in the class:

Example

#include <iostream> using namespace std; class Box { public: double length; // Length double breadth; // Width double height; // Height // Member function declaration double getVolume(void); void setLength( double len ); void setBreadth( double bre ); void setHeight( double hei ); }; // Member function definition double Box::getVolume(void) { return length * breadth * height; } void Box::setLength( double len ) { length = len; } void Box::setBreadth( double bre ) { breadth = bre; } void Box::setHeight( double hei ) { height = hei; } // The main function of the program int main( ) { Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box double volume = 0.0; // Used to store volume // Box 1 details Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // Box 2 details Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // Volume of box 1 volume = Box1.getVolume(); cout << "Volume of Box1:" << volume <<endl; // Volume of box 2 volume = Box2.getVolume(); cout << "Volume of Box2:" << volume <<endl; return 0; }

When the above code is compiled and executed, it produces the following results:

Box1 的体积: 210
Box2 的体积: 1560

C++ Classes & Objects

other extensions