class TConst
{
const int i;
int& ref;
public:
TConst(int n):i(n),ref(n){}
static void p1(){prn(i);}//error here
};
当我尝试在static
成员函数中使用const
类成员时,编译器生成错误。为什么我们不能在静态成员函数中使用const成员?
为什么不允许?
class TConst
{
const int i;
int& ref;
public:
TConst(int n):i(n),ref(n){}
static void p1(){prn(i);}//error here
};
当我尝试在static
成员函数中使用const
类成员时,编译器生成错误。为什么我们不能在静态成员函数中使用const成员?
为什么不允许?
const
成员在对象构造期间被初始化。 static
成员不依赖于对象创建,并且无权访问this
指针,因此他们不知道const
成员变量所在的位置。
即使它不是const
这是行不通的:
error: a nonstatic member reference must be relative to a specific object
静态函数不能访问非静态成员变量。这是因为非静态成员变量必须属于一个类对象,并且静态成员函数没有类对象来处理。
const
意味着不同的事情。在这种情况下,这意味着i
在初始化后是不可变的。它不意味着它是一个字面常量(就像我相信你认为它的意思)。 i
对于TConst
的不同实例可以是不同的,所以static
方法不能使用它是合乎逻辑的。
它总是这么简单)谢谢 – Alexander 2011-12-28 18:12:01
请始终发布您获得的完整错误。 – orlp 2011-12-28 18:05:49
const int仍然绑定到一个对象,而不是类。 – nullpotent 2011-12-28 18:07:09
在一个静态方法中没有类实例,所以没有类成员...只要你想这样使用这个'static const int i = 42;'。 – AJG85 2011-12-28 18:12:50