常成員函數,是指由const修飾符修飾的成員函數,在常成員函數中不得修改類中的任何數據成員的值。常成員函數表示成員函數隱含傳入的this指針爲const指針,決定了在該成員函數中,任意修改它所在的類的成員的操作都是不允許的(因爲隱含了對this指針的const引用),唯一的例外是對於mutable修飾的成員。
常成員函數示例
class CTest2
{
public:
int GetValue() const
{
return m_iValue;
}
int m_iValue;
};
常成員函數使用注意事項
1. 非成員函數或靜態成員函數,不能用const修飾
2. 常成員函數中,唯一可以修改的成員變量是mutable修飾的成員變量
3. 當一個類的對象被聲明爲常對象,則不能通過該對象調用該類中的非const成員函數
4. 加了const的成員函數可以被非const對象和const對象調用,但不加const的成員函數只能被非const對象調用
常成員函數使用的注意事項的示例程序,如下
#include <iostream>
#include <string>
void PrintHello() const //編譯報錯,error C2270: 'PrintTitle': modifiers not allowed on nonmember functions
{
std::cout << "Hello World" << std::endl;
}
class CTest
{
public:
CTest()
: m_iValue(-1)
{
}
virtual ~CTest()
{
}
void ValueAdd1() const //編譯報錯,error C3490: 'm_iValue' cannot be modified because it is being accessed through a const object
{
m_iValue = m_iValue + 1;
m_strValue = "test"; //該處不會編譯報錯,是因爲m_strValue聲明是在前面加了mutable
}
void PrintValue() const
{
std::cout << m_iValue << std::endl;
}
void PrintHi()
{
std::cout << "Hi World" << std::endl;
}
void CallPrint1()
{
PrintValue();
PrintHi();
}
void CallPrint2() const
{
PrintValue();
PrintHi(); //編譯錯誤,error C2662: 'void CTest::PrintHi(void)': cannot convert 'this' pointer from 'const CTest' to 'CTest &'
}
int m_iValue;
mutable std::string m_strValue;
};
int main()
{
CTest Test1;
Test1.PrintValue();
Test1.ValueAdd1();
Test1.PrintValue();
Test1.PrintHi();
const CTest Test2;
Test2.PrintValue();
Test2.ValueAdd1();
Test2.PrintValue();
Test2.PrintHi(); //編譯錯誤,error C2662: 'void CTest::PrintHi(void)': cannot convert 'this' pointer from 'const CTest' to 'CTest &'
system("pause");
}
爲什麼使用常成員函數?
我們定義的類的成員函數中,常常有一些成員函數不改變類的數據成員,也就是說,這些函數是"只讀"函數,而有一些函數要修改類數據成員的值。如果把不改變數據成員的函數都加上const關鍵字進行標識,顯然,可提高程序的可讀性。其實,它還能提高程序的可靠性,已定義成const的成員函數,一旦企圖修改數據成員的值,則編譯器按錯誤處理。將成員函數聲明爲常成員函數也能防止產生const對象無法調用該成員函數的問題。