静态类成员的初始化 [英] Initialization of Static Class members
本文介绍了静态类成员的初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我尝试初始化 obj_s
它要求我使它 const
- 我不能这样做必须保留我创建对象的数量。
If i try to initialize obj_s
it asks me to make it const
- and i cant do that for i have to keep count of my Created Objects.
#include<iostream>
class A
{
static int obj_s=0;
public:
A(){ ++obj_s;cout << A::obj_s << "\nObject(s) Created\n"; }
};
int main()
{
A a,b,c,d;
}
下面的代码会给出以下错误:
The code below keeps giving me the following error:
[Linker error] undefined reference to `A::obj_s'
推荐答案
[已解决]
代码提供错误,在第二种情况下创建,并且在其第一次它不初始化,它的应该的方式 -
这里是固定的代码:
The code is giving the error because the object is not getting created in the second case, and in the first its not initializing, the way its supposed to - Here's the fixed Code:
#include<iostream>
class A
{
static int obj_s;
public:
A()
{ obj_s++; std::cout << A::obj_s << "\nObject(s) Created\n" ; }
};
int A::obj_s=0; // This is how you intialize it
int main()
{
A a ,b,c,d;
}
这篇关于静态类成员的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文