是的,C++中的常量成員函數(shù)可以訪問靜態(tài)成員。常量成員函數(shù)(const member function)是不能修改對象狀態(tài)的成員函數(shù),而靜態(tài)成員是屬于類而不是類的某個對象的,因此它們在整個類中都是可見的。在常量成員函數(shù)中訪問靜態(tài)成員是安全的,因為靜態(tài)成員與類的任何特定對象無關(guān)。
以下是一個簡單的示例:
#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
的類,它具有一個靜態(tài)成員static_member
和兩個成員函數(shù):non_const_member_function
和const_member_function
。const_member_function
是一個常量成員函數(shù),它可以訪問靜態(tài)成員static_member
。