Home > Article > Backend Development > What is the scope of C++ static functions?
The scope of a static function is different from that of a non-static member function. It can call and access member variables and non-member variables without an object: 1. Only member variables declared with static can be accessed; 2. Global variables can be accessed variables or variables in other namespaces.
C Scope of static functions
The scope of static functions is different from that of non-static member functions. It can access both member and non-member variables, and can be called without an object.
Access to member variables
Only member variables declared with the static keyword can be accessed in static functions. By default, member variables are non-static and cannot be accessed within static functions.
Access to non-member variables
Static functions can also access global variables or variables in other namespaces.
Example
The following is an example class with static functions:
class Example { public: static int x; // 静态成员变量 static void print_x() { std::cout << x << std::endl; } }; int Example::x = 10; // 静态成员变量的定义 int main() { Example::print_x(); // 可以直接调用静态函数 return 0; }
In this example, print_x()
Can be called without creating any Example
object. The function accesses the static member variable x
and prints its value.
Advantages
Static functions have the following advantages:
The above is the detailed content of What is the scope of C++ static functions?. For more information, please follow other related articles on the PHP Chinese website!