在c++中创建一个静态类计数器(java示例)
create a static sort of class counter in c++ (java example)
以下是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
相关文章:
- 我正在尝试在我的类中创建一个静态成员,但编译器警告我它是未定义的
- 如何创建一个静态类来引用带有C++的字符串变量
- 长镜头 -- 可能有一个静态类成员,该类成员具有访问非静态成员的 lambda
- 使用类模板参数推导来创建一个静态接口
- 在抽象类中,可以使用抽象类A的类型创建一个静态字段
- 如何创建一个编译时静态类类型,该类型初始化具有特定值的成员容器
- 一个类本身有一个静态成员的功能是什么?
- 如果我在一个类中有一个静态属性,并创建该类的许多新实例
- 在头文件中声明一个静态类成员
- C++在类中声明一个静态对象
- 在另一个类中创建一个静态类变量,使用已删除的函数 = 错误
- 如果一个类不是直接从main中使用的,但有一个静态私有成员,那么在编译和链接时,可以使用最大优化来忽略它吗
- 如何让一组不同的子类对象从另一组共享基类的一个静态变量
- 是否可以在模板类中编写一个静态可变参数模板函数,该函数能够接受 T 类型的 N 个参数?
- 如何在多个类之间传递一个静态对象
- 在c++中创建一个静态类计数器(java示例)
- 在C++中,一个静态变量可以在没有类的情况下存在吗
- 为什么我可以在一个文件中无序地初始化两个静态类变量,而不能初始化三个
- 另一个类中使用的非静态类<未解析的重载函数类型>
- 在类模板中定义一个静态数组