是的,C++中的常量成员函数可以访问静态成员。常量成员函数(const member function)是不能修改对象状态的成员函数,而静态成员是属于类而不是类的某个对象的,因此它们在整个类中都是可见的。在常量成员函数中访问静态成员是安全的,因为静态成员与类的任何特定对象无关。
以下是一个简单的示例:
#include <iostream>
class MyClass {
public:
static int static_member;
void non_const_member_function() {
std::cout << "Accessing static member from non-const member function: " << static_member << std::endl;
}
void const_member_function() const {
std::cout << "Accessing static member from const member function: " << static_member << std::endl;
}
};
int MyClass::static_member = 10;
int main() {
MyClass obj;
obj.non_const_member_function(); // Output: Accessing static member from non-const member function: 10
obj.const_member_function(); // Output: Accessing static member from const member function: 10
return 0;
}
在这个例子中,我们有一个名为MyClass
的类,它具有一个静态成员static_member
和两个成员函数:non_const_member_function
和const_member_function
。const_member_function
是一个常量成员函数,它可以访问静态成员static_member
。