我正在尝试:
class MyClass {
public:
MyClass();
int myID;
static int currentID;
};
MyClass::MyClass() {
myID = currentID;
++currentID;
}
我正在尝试为此类的所有实例分配一个唯一 ID。
编辑:
这对我不起作用。我在 xcode 中得到了其中两个:
undefined symbol : “GameObject::currentID”,引用自: GameObject.o 中的 __ZN10GameObject9currentIDE$non_lazy_ptr (也许你的意思是:__ZN10GameObject9currentIDE$non_lazy_ptr) ld:未找到符号 collect2: ld 返回 1 个退出状态
最佳答案
对我有用:
#include <iostream>
class My
{
public:
My() : id(++currentId) {}
int id;
static int currentId;
};
int My::currentId = 0;
std::ostream & operator<<(std::ostream & os, My & m)
{
return os << m.id;
}
int main()
{
My a;
My b;
My c;
std::cout << a << std::endl;
std::cout << b << std::endl;
std::cout << c << std::endl;
}
输出:
> ./x
1
2
3
关于c++ - 在 C++ 中,是否可以在构造函数中访问静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8367503/