为什么我们不能在静态成员函数中使用const成员?

Ale*_*der 9 c++ static-methods const

class TConst
{
    const int i;
    int& ref;
    public:
    TConst(int n):i(n),ref(n){}
    static void p1(){prn(i);}//error here
};
Run Code Online (Sandbox Code Playgroud)

当我尝试conststatic成员函数中使用类成员时,我的编译器会生成错误.

为什么不允许?

ten*_*our 13

const意味着不同的东西 在这种情况下,它意味着i在初始化之后它是不可变的.这并不意味着它是一个字面常量(就像我相信你认为它意味着).i对于不同的实例可以是不同的TConst,因此static方法不能使用它是合乎逻辑的.


Igo*_*Oks 7

即使它不是,它也行不通const:

error: a nonstatic member reference must be relative to a specific object
Run Code Online (Sandbox Code Playgroud)

静态函数无法访问非静态成员变量.这是因为非静态成员变量必须属于类对象,而静态成员函数没有要使用的类对象.


Kar*_*son 6

const在对象构造期间初始化该成员.该static成员是不依赖于对象的创建和没有访问this指针,因此他们不知道你的const成员变量所在.