是的,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
。