分配给的直接静态数据成员需要定义。基本上定义分配内存。是这样的:
class C
{
private:
static int i; // pure declaration
public:
static auto n_instances() -> int { return i; }
~C() { --i; }
C(){ ++i; }
C(C const&) { ++i; }
};
int C::i; // definition
在头文件是不切实际的(如果报头在多个翻译单位使用这将是违反了一个定义规则,与链接器抱怨),这样的话就可以使用以下技术:
class C
{
private:
static auto n()
-> int&
{
static int the_count = 0;
return the_count;
}
public:
static auto n_instances() -> int { return n(); }
~C() { --n(); }
C(){ ++n(); }
C(C const&) { ++n(); }
};
还有其他方法可以做到这一点,包括模板技巧和C++ 17个inline
数据。
我选择使用int
,而不是unsigned
因为int
有利于整数数字,而unsigned
是好位层次的东西,而不是相反。
声明:代码没有被编译器触及。
只需在类声明后添加'unsigned int C :: i = 0;'就可以工作了 –
另外,http://stackoverflow.com/questions/15845745/lnk2001-error-when-accessing-static-variables- c,http://stackoverflow.com/questions/16049306/error-lnk2001-unresolved-external-symbol-private-static-class和许多其他许多人。 – AnT