我们可以在非静态成员函数中使用静态数据成员吗? [英] can we use the static data member in the non static member function?
本文介绍了我们可以在非静态成员函数中使用静态数据成员吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include iostream.h // Brackets removed
#include conio.h // Brackets removed
class X
{
static int x;
public:
void fun()
{
cout<<x;
}
};
int main()
{
X o;
o.fun();
getch();
return 0;
}
推荐答案
是的.静态类成员可用于任何类实例.
您不能做的是从静态方法中引用普通成员,因为该方法没有"this"指针.
Yes you can. The static class member is available to any class instance.
What you cannot do is reference a plain member from a static method, because the method doesn''t have the ''this'' pointer.
是的,请不要忘记初始化您的静态对象(如果您在标头中执行此操作,请不要忘记标头保护符,这样它就不会被多次包含):
Yes, just don''t forget to initialize your static (if you''re doing it in the header, don''t forget header guards so it doesn''t get included more than once):
#ifndef MYCLASS_X
#define MYCLASS_X
class X
{
static int x;
public:
void fun()
{
cout<<x;
}
};
int X::x = 0;
#endif //MYCLASS_X
如果在X的构造函数中初始化x的值,则可以.如果不初始化,我不确定会发生什么,但是我认为您会在这种情况下会产生错误.
You can if you initialize the value of x in the constructor for X. If you don''t, I''m not sure what would happen, but I think you would generate an error in that situation.
这篇关于我们可以在非静态成员函数中使用静态数据成员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文