我尝试使用以下方法计算类的实例数:
class shelf
{
private:
static int count_instances = 0 ;
book b1;
public :
shelf() {
count_instances++;
cout << "this is the "<<count_instances<<" instance"<<endl;
}
};
main (){
shelf s1;
}
但是得到了编译错误: ISO c ++禁止非const静态成员的类内初始化。
虽然以下安排似乎有效
class shelf
{
private:
static int count_instances ;
book b1;
public :
shelf() {
count_instances++;
cout << "this is the "<<count_instances<<" instance"<<endl;
}
};
int shelf::count_instances =0;
main (){
shelf s1;
}
有人可以帮助我理解吗?还有什么是计算类的实例数的正确方法