#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
         this->objectCount++;
      }

      double Volume() {
         return length * breadth * height;
      }

      static int getID()
      {
          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) {
   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;
   cout << "Box1 ID: " << Box1.getID() << endl;
   cout << "Box2 ID: " << Box2.getID() << endl;

   return 0;
}


如何访问“ Box1”和“ Box2”的objectCount。 “ Box1”的objectCount应该为1,而“ Box2”仍为2。例如

它打印:


  构造函数称为。
  构造函数称为。
  物件总数:2
  Box1 ID:2
  Box2 ID:2


代替:


  构造函数称为。
  构造函数称为。
  物件总数:2
  Box1 ID:1
  Box2 ID:2

最佳答案

该课程只有一个objectCount。根据定义,这就是static类成员。

您需要做的是向该类添加一个非静态成员,然后在构造函数中对其进行初始化。

 static int objectCount;
 int my_objectCount;

  // Constructor definition
  Box(double l = 2.0, double b = 2.0, double h = 2.0)
     : my_objectCount(++objectCount)
  {
    // ...
  }


然后,对于该类的第一个实例,my_objectCount将为1,对于第二个实例,将为2,依此类推。

关于c++ - 如何为类对象的每个实例访问静态变量值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43015830/

10-12 17:18
查看更多