Rya*_*yan 3 c++ static constructor
我在尝试:
class MyClass {
public:
MyClass();
int myID;
static int currentID;
};
MyClass::MyClass() {
myID = currentID;
++currentID;
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试为此类的所有实例分配一个唯一的ID.
编辑:
它对我不起作用.我在xcode中得到了两个:
未定义的符号:"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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
> ./x
1
2
3
Run Code Online (Sandbox Code Playgroud)