C++ 静态成员函数

17 Mar 2025 | 5 分钟阅读

static 是 C 和 C++ 编程语言中的一个关键字。我们使用 static 关键字在类的内部和外部定义静态数据成员或静态成员函数。让我们通过程序来理解静态数据成员和静态成员函数。

Static Member Function in C++

静态数据成员

当我们使用 static 关键字定义类的成员变量时,这些成员变量被称为静态数据成员。静态数据成员与静态成员函数类似,因为静态数据只能通过静态数据成员或静态成员函数访问。并且,类的所有对象共享同一份静态成员副本以访问静态数据。

语法

在这里,static 是预定义库中的一个关键字。

data_type 是 C++ 中的变量类型,例如 int、float、string 等。

data_member 是静态数据的名称。

示例 1: 让我们创建一个简单的程序来访问 C++ 编程语言中的静态数据成员。

输出

Enter the Id of the Car: 
101
Enter the name of the Car: 
Ferrari
Number of the Marks (1 - 10): 
10

Id of the Car: 101 
Name of the Car: Ferrari 
Marks: 10

Enter the Id of the Car: 
205
Enter the name of the Car: 
Mercedes
Number of the Marks (1 - 10): 
9

Id of the Car: 205 
Name of the Car: Mercedes 
Marks: 9
No. of objects created in the class: 2

静态成员函数

静态成员函数是用于访问静态数据成员或其他静态成员函数的特殊函数。成员函数使用 static 关键字定义。静态成员函数与类的任何数量的对象共享同一份成员函数副本。我们可以使用类名或类的对象访问静态成员函数。如果静态成员函数访问任何非静态数据成员或非静态成员函数,它将抛出错误。

语法

在这里,class_name 是类的名称。

function_name:函数名是静态成员函数的名称。

parameter:它定义了传递给静态成员函数的参数名称。

示例 2: 让我们创建另一个程序来使用 C++ 编程语言中的类名访问静态成员函数。

输出

The value of the num is: 5

示例 3: 让我们创建另一个程序来使用 C++ 编程语言中的类对象访问静态成员函数。

输出

The value of the num is: 15

示例 4: 让我们考虑一个示例,在 C++ 编程语言中使用对象和类访问静态成员函数。

输出

Print the static member through object name:
The value of the A is: 20
The value of the B is: 30
The value of the C is: 40   
Print the static member through the class name:
The value of the A is: 20
The value of the B is: 30
The value of the C is: 40