静态函数调用

静态函数

#include <iostream.h>
class Point
{
 public:
     void output()//非静态成员函数
     {
     }
    static void init()//静态成员函数
    {
    }
};

调用1:非静态成员函数和非静态成员属于对象的方法和数据,也就是先产生类的对象,然后通过类的对象去引用。

void main()
{
  Point pt;
  pt.init();//编译成功
  pt.output();//编译成功
 }

调用2:静态成员函数和静态成员变量属于类本身,在类加载的时候,即为它们分配了空间,所以可通过类名::函数名,类名::变量名来访问。

void main()
{
  Point::init();//编译成功。不属于某个具体的对象,Point类没有构造对象之前,init已经存在,即分配了代码区空间。
  Point::output();//编译失败。非法调用非静态成员函数,即Point构造对象后,output才存在。
 }

调用3:静态成员函数只能调用静态成员变量。

#include <iostream.h>
class Point
{
 public:
     void output()//非静态成员函数
     {
      x = 0;   
      y = 0;
     }
    static void init()//静态成员函数
    {
      x = 0;   //静态成员函数调用非静态成员
      y = 0;
    }
 private:
    int x, y; //非静态成员
};
void main()
{
  Point::init();//编译失败。静态成员函数不能调用非静态成员的成员函数和成员变量。init已存在,x,y不存在。
  Point pt;//构造pt对象时,给x,y分配内存空间,给output分配代码区空间。
  pt.output();//编译成功。
 }

函数之间的引用许可,内存模型: 无论采什么样的操作,程序代码都是在内存中运行的,只有在内存中占有了一席之地,我们才能够访问它。如果一个成员函数或成员变量还未在内存中产生,结果是无法访问它的。

调用4:类外初始化静态成员变量。非静态成员函数可以调用静态成员函数。

#include <iostream.h>
int Point::x = 0;
int Point::y = 0;//类外初始化静态成员变量
class Point
{
 public:
     void output()//非静态成员函数
     {
       init();  //非静态成员函数调用静态成员函数
     }
    static void init()//静态成员函数
    {
      x = 0;   //静态成员函数调用静态成员
      y = 0;
    }
 static int x, y;   //静态成员变量
};
void main()
{
  Point::init();//编译成功。
  Point pt;
  pt.output();//编译成功。
}
发布了38 篇原创文章 · 获赞 1 · 访问量 1877

猜你喜欢

转载自blog.csdn.net/qq_36633275/article/details/103907384
今日推荐