[C++] 类中的静态成员

代码部分转载自:C++ 类的静态成员及静态成员函数

1、类的静态成员与类本身相关,与类的各个对象无关,它存在于任何对象之外,所有的对象共享静态成员,所以在计算对象大小时,不包含静态数据成员。
2、静态成员函数不能声明为const的,因为这样非const对象就不能使用了;并且不包含this指针,因为this指针是针对具体对象的,这样静态成员函数就不能调用非静态成员
3、静态数据成员不属于类的任何一个对象,不是由类的构造函数初始化的,必须在类的外部定义和初始化每个静态成员。
4、静态数据成员一旦被定义,就将一直存在于程序的整个生命周期中。
5、下面通过几个例子来总结静态成员变量和静态成员函数的使用规则。

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

//例子一:通过类名调用静态成员函数和非静态成员函数
class Point{
public:
    void init()
    {}

    static void output()
    {}
};

void main()
{
    Point::init();
    Point::output();
}

编译出错:错误 1 error C2352: “Point::init”: 非静态成员函数的非法调用

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

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

//例子二:通过类的对象调用静态成员函数和非静态成员函数
class Point{
public:
    void init()
    {
    }

    static void output()
    {}
};

void main()
{
    Point pt;
    pt.init();
    pt.output();
}

 编译通过。

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

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

//例子三:在类的静态成员函数中使用类的非静态成员
#include <iostream>
using namespace std;

class Point{
public:
    void init()
    {
    }
    static void output()
    {
        cout << "m_x=" << m_x << endl;
    }
private:
    int m_x;
};
void main()
{
    Point pt;
    pt.output();
}

 编译出错:IntelliSense: 非静态成员引用必须与特定对象相对

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

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

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

//例子四:在类的非静态成员函数中使用类的静态成员
#include <iostream>
using namespace std;

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

编译通过。

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

五、使用类的静态成员变量

//例子五:使用类的静态成员变量
#include <iostream>
using namespace std;

class Point{
public:
    Point()
    {
        m_nPointCount++;
    }
    ~Point()
    {
        m_nPointCount++;
    }
    static void output()
    {
        cout << "m_nPointCount=" << m_nPointCount << endl;
    }
private:
    static  int m_nPointCount;
};

void main()
{
    Point pt;
    pt.output();
}

链接出错:error LNK2001: 无法解析的外部符号 "private: static int Point::m_nPointCount" (?m_nPointCount@Point@@0HA)

这是因为类的成员变量在使用前必须先初始化。

改成如下代码即可:

#include <iostream>
using namespace std;

class Point{
public:
    Point()
    {
        m_nPointCount++;
    }
    ~Point()
    {
        m_nPointCount++;
    }
    static void output()
    {
        cout << "m_nPointCount=" << m_nPointCount << endl;
    }
private:
    static  int m_nPointCount;
};

//类外初始化静态成员变量时,不用带static关键字
int Point::m_nPointCount = 0;
void main()
{
    Point pt;
    pt.output();
}

结论五:类的静态成员变量必须先初始化再使用。

原文地址:https://www.cnblogs.com/zhizhiyu/p/10153103.html