using namespace std;
class test{
private:
int a,b;
public:
static int count=0;
test(int a=10,int b=10){
count++;
}
};
int main(){
test t;
cout<<t.count<<endl;
test t1;
cout<<t1.count<<endl;
}我使用了静态成员,它是在类内初始化的,我在类之外尝试过--它工作得很好,但是我不知道为什么首先要初始化类中的成员,这是一个错误。
当我运行上述代码时,它会给出以下错误:ISO C++禁止在类中初始化非const静态成员'test::count'.。
为什么我不能在类中初始化静态成员?
发布于 2022-07-19 07:18:08
错误很明显,您不能在声明变量时初始化它们。
相反,将它们声明为普通(没有初始化),然后记住在类之外添加它们的定义,并使用实际的初始化:
class test{
private:
int a,b;
public:
static int count;
test(int a=10,int b=10){
count++;
}
};
int test::count=0;从C++17标准中添加了静态成员变量的内联定义和初始化:
class test{
private:
int a,b;
public:
inline static int count=0; // Note the inline keyword
test(int a=10,int b=10){
count++;
}
};https://stackoverflow.com/questions/73032610
复制相似问题