Loading

C++有关class内部的static关键字理解

变量

在class中被static修饰的成员变量是可以被直接访问的,不需要实例化。
并且所有实例共享同一份该变量,进而可实现单例模式。
如果换个理解方式,class仅提供一个namespace而变量实际存在于class之外,
这就不难理解为什么头文件中定义的class static变量需要在cpp中单独声明。

class MLP
{
public:
    static float max_coeff;
}

float MLP::max_coeff = 0.0f;

方法

C++中规定class的static方法不能调用non-static成员,为什么?
本质上讲class其实是c++提供的语糖,编译器最终生成的结果是包含成员变量的struct
原本class内部的方法则演变为将struct作为入参的外部函数。
举个例子:

class MLP
{
public:
    static void static_set_layers(const int& layers);
    void set_layers(const int& layers);
private:
    int layers;
}

在编译器眼里大概是:

struct MLP
{
    int layers;
};

void MLP_static_set_layers(const int& layers);

void MLP_set_layers(MLP* this, const int& layers);

区别在于成员函数转换后隐式入参this指针,进而可以修改成员变量。
而static方法直接不包含this入参,自然也就无法更改non-static成员的值。

posted @ 2022-12-13 15:59  azureology  阅读(311)  评论(0编辑  收藏  举报