当前位置:   article > 正文

C++中的静态成员变量和静态成员函数

C++中的静态成员变量和静态成员函数

一、静态成员变量

静态成员变量使用static修饰的成员变量。静态成员变量不属于某一个对象,而是属于整个类,因此静态成员变量不能设置缺省值,因为缺省值是给予初始化列表用于初始化对象的。

静态成员变量需要再类内声明,类外定义。

  1. class A {
  2. public:
  3. static int _n;//类内声明
  4. };
  5. int A::_n = 0;//类外定义

静态成员变量属于整个类,因此静态成员变量既可以用对象访问,也可以使用类访问(公有属性情况下)。

  1. int main()
  2. {
  3. A aa1;
  4. A aa2;
  5. cout << aa1._n << endl;//对象访问
  6. cout << aa2._n << endl;//对象访问
  7. cout << A::_n << endl;//类访问
  8. return 0;
  9. }

 如果静态成员变量是私有属性的,可以设置Get接口。

  1. class A {
  2. private:
  3. static int _n;//类内声明
  4. public:
  5. int GetN()
  6. {
  7. return _n;
  8. }
  9. };
  10. int A::_n = 0;//类外定义
  11. int main()
  12. {
  13. A aa1;
  14. A aa2;
  15. cout << aa1.GetN() << endl;
  16. cout << aa2.GetN() << endl;
  17. return 0;
  18. }

二、静态成员函数

静态成员函数就是用static修饰的成员函数。静态成员函数与普通成员函数不同点在于,静态成员函数没有this指针,因此静态成员函数只能访问静态成员变量,不能访问普通成员变量。

  1. class A {
  2. private:
  3. static int _n;//类内声明
  4. public:
  5. static int GetN()//静态成员函数
  6. {
  7. return _n;
  8. }
  9. };
  10. int A::_n = 0;//类外定义
  11. int main()
  12. {
  13. A aa1;
  14. A aa2;
  15. cout << aa1.GetN() << endl;
  16. cout << aa2.GetN() << endl;
  17. cout << A::GetN() << endl;
  18. return 0;
  19. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/197862
推荐阅读
  • 相关标签
      

    闽ICP备14008679号