在c++中创建一个静态类计数器(java示例)

create a static sort of class counter in c++ (java example)

本文关键字:一个 静态类 计数器 示例 java c++ 创建      更新时间:2023-10-16

以下是java:中的片段

class C {
    private static int c = 0;
    C(){ c++; }
    public static int getC () { return c; }
}
public class TestC {
    public static void main (...) {
        C c1 = new C();
        C c2 = new C();
        // at this point C.getC() returns 2(int)
    }
}

现在我想用C++做一些类似的事情,我对课堂写作有了基本的理解,实现计数器的最短代码片段应该是什么?

这是我的示例类:

class C {
    public:

    private:
}
int main () {
    C c1;
    C c2;
    // printing the counter like C.getC();
}

非常相似。

在相关标题中:

class C {   
    private:
         static int c;  // Declaration of c.
    public:
         C(){ c++; }
         static int getC () { return c; }
};

一个.cpp文件中:

int C::c = 0;  // Definition of c.

关键是要在一个地方(即不在标题中)提供c的定义,否则会出现链接错误。

class user
{
  private:
  int id;
  static int next_id;
  public:
  static int getCount()
  {    
    return next_id;
  }
  /* More stuff for the class user */
  user()
  {
    id = user::next_id++; //
  }
};
int user::next_id = 0;

从此链接http://www.cprogramming.com/tutorial/statickeyword.html

相关文章: