当前位置: 网站首页>小程序开发>网站开发

灯塔设计网页公司

发表日期: 2022-07-30 16:13:28 浏览次数:44

灯塔设计网页公司

网站建设.png

3.1 在 C++ 中

static 关键字最基本的用法是:

  • 1、被 static 修饰的变量属于类变量,可以通过类名.变量名直接引用,而不需要 new 出一个类来

  • 2、被 static 修饰的方法属于类方法,可以通过类名.方法名直接引用,而不需要 new 出一个类来

被 static 修饰的变量、被 static 修饰的方法统一属于类的静态资源,是类实例之间共享的,换言之,一处变、处处变。

在 C++ 中,静态成员是属于整个类的而不是某个对象,静态成员变量只存储一份供所有对象共用。所以在所有对象中都可以共享它。使用静态成员变量实现多个对象之间的数据共享不会破坏隐藏的原则,保证了安全性还可以节省内存。

静态成员的定义或声明要加个关键 static。静态成员可以通过双冒号来使用即 <类名>::<静态成员名>

3.2 静态类相关

通过类名调用静态成员函数和非静态成员函数:

class Point  {  public:      void init()      {        }      static void output()      {      }  };  void main()  {      Point::init();      Point::output();  }

报错:

'Point::init' : illegal call of non-static member function

结论 1:不能通过类名来调用类的非静态成员函数。

通过类的对象调用静态成员函数和非静态成员函数。

class Point  {  public:      void init()      {        }      static void output()      {      }  }; void main()  {      Point pt;      pt.init();      pt.output();  }

编译通过。

结论 2:类的对象可以使用静态成员函数和非静态成员函数。

在类的静态成员函数中使用类的非静态成员。

#include <stdio.h>  


;  

    pt.init();  

    pt.output();  

}

编译通过。


结论 2:类的对象可以使用静态成员函数和非静态成员函数。


在类的静态成员函数中使用类的非静态成员。


#include <stdio.h>  

class Point  

{  

public:   

    void init()  

    {    

    }  

    static void output()  

    {  

        printf("%d\n", m_x);  

    }  

private:  

    int m_x;  

};  

void main()  

{  

    Point pt;  

    pt.output();  

}

编译出错:


error C2597: illegal reference to data member 'Point::m_x' in a static member function

因为静态成员函数属于整个类,在类实例化对象之前就已经分配空间了,而类的非静态成员必须在类实例化对象后才有内存空间,所以这个调用就出错了,就好比没有声明一个变量却提前使用它一样。


结论3:静态成员函数中不能引用非静态成员。


在类的非静态成员函数中使用类的静态成员。


class Point  

{  

public:   

    void init()  

    {    

        output();  

    }  

    static void output()  

    {  

    }  

};  

void main()  

{  

    Point pt;  

    Pt.init();

    pt.output();  

}

编译通过。


结论 4:类的非静态成员函数可以调用用静态成员函数,但反之不能。


使用类的静态成员变量。


灯塔设计网页公司

400-111-6878
服务热线
顶部

备案号: 苏ICP备11067224号

CopyRight © 2011 书生商友信息科技 All Right Reserved

24小时服务热线:400-111-6878   E-MAIL:1120768800@qq.com   QQ:1120768800

  网址: https://www.768800.com  网站建设上往建站

关键词: 网站建设| 域名邮箱| 服务器空间| 网站推广| 上往建站| 网站制作| 网站设计| 域名注册| 网络营销| 网站维护|

企业邮箱| 虚拟主机| 网络建站| 网站服务| 网页设计| 网店美工设计| 网站定制| 企业建站| 网站设计制作| 网页制作公司|

400电话办理| 书生商友软件| 葬花网| 调温纤维| 海洋馆运营维护| 北京保安公司| 殡仪馆服务| 殡葬服务| 昌平殡葬| 朝阳殡葬|

预约专家

欢迎您免费咨询,请填写以下信息,我们收到后会尽快与您联系

  

服务热线:400-111-6878