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)
当我尝试const在static成员函数中使用类成员时,我的编译器会生成错误.
为什么不允许?
ten*_*our 13
const意味着不同的东西 在这种情况下,它意味着i在初始化之后它是不可变的.这并不意味着它是一个字面常量(就像我相信你认为它意味着).i对于不同的实例可以是不同的TConst,因此static方法不能使用它是合乎逻辑的.
即使它不是,它也行不通const:
error: a nonstatic member reference must be relative to a specific object
Run Code Online (Sandbox Code Playgroud)
静态函数无法访问非静态成员变量.这是因为非静态成员变量必须属于类对象,而静态成员函数没有要使用的类对象.
| 归档时间: |
|
| 查看次数: |
1138 次 |
| 最近记录: |