...
Here's an example of a static member function:
Code Block | ||
---|---|---|
| ||
#include <iostream> using namespace std; // Define a class named "MyClass" class MyClass { private: int x; // Private member variable public: // Constructor that initializes "x" MyClass(int x) : x(x) {} // Static member function that prints a message to the console static void printMessage() { cout << "This is a static function." << endl; } // Static member function that squares an integer and returns the result static int square(int num) { return num * num; } }; // The main function int main() { // Call the static member function "printMessage" using the class name MyClass::printMessage(); // Call the static member function "square" using the class name // and assign the result to a variable named "result" int result = MyClass::square(5); // Print the result to the console cout << result << endl; return 0; } |
...