目录

静态成员(Static Members of a Class)

我们可以使用static关键字定义类成员static。 当我们将类的成员声明为static时,意味着无论创建了多少个类的对象,都只有一个静态成员的副本。

静态成员由类的所有对象共享。 如果没有其他初始化,则在创建第一个对象时,所有静态数据都将初始化为零。 我们不能把它放在类定义中,但它可以在类之外初始化,如下例所示,通过重新声明静态变量,使用范围解析运算符::来标识它属于哪个类。

让我们尝试以下示例来理解静态数据成员的概念 -

#include <iostream>
using namespace std;
class Box {
   public:
      static int objectCount;
      // Constructor definition
      Box(double l = 2.0, double b = 2.0, double h = 2.0) {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
         // Increase every time object is created
         objectCount++;
      }
      double Volume() {
         return length * breadth * height;
      }
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};
// Initialize static member of class Box
int Box::objectCount = 0;
int main(void) {
   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2
   // Print total number of objects.
   cout << "Total objects: " << Box::objectCount << endl;
   return 0;
}

编译并执行上述代码时,会产生以下结果 -

Constructor called.
Constructor called.
Total objects: 2

静态功能成员

通过将函数成员声明为static,可以使其独立于类的任何特定对象。 即使没有类的对象存在,也可以调用静态成员函数,并且仅使用类名和范围解析运算符::来访问static函数。

静态成员函数只能访问静态数据成员,其他静态成员函数以及类外部的任何其他函数。

静态成员函数具有类作用域,并且它们无权访问该类的this指针。 您可以使用静态成员函数来确定是否已创建类的某些对象。

让我们尝试以下示例来理解静态函数成员的概念 -

#include <iostream>
using namespace std;
class Box {
   public:
      static int objectCount;
      // Constructor definition
      Box(double l = 2.0, double b = 2.0, double h = 2.0) {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
         // Increase every time object is created
         objectCount++;
      }
      double Volume() {
         return length * breadth * height;
      }
      static int getCount() {
         return objectCount;
      }
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};
// Initialize static member of class Box
int Box::objectCount = 0;
int main(void) {
   // Print total number of objects before creating object.
   cout << "Inital Stage Count: " << Box::getCount() << endl;
   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2
   // Print total number of objects after creating object.
   cout << "Final Stage Count: " << Box::getCount() << endl;
   return 0;
}

编译并执行上述代码时,会产生以下结果 -

Inital Stage Count: 0
Constructor called.
Constructor called.
Final Stage Count: 2
↑回到顶部↑
WIKI教程 @2018