C++常成員函式
阿新 • • 發佈:2018-12-12
宣告:<型別標誌符>函式名(引數表)const;
說明:
(1)const是函式型別的一部分,在實現部分也要帶該關鍵字。
(2)const關鍵字可以用於對過載函式的區分。
(3)常成員函式不能更新類的成員變數,也不能呼叫該類中沒有用const修飾的成員函式,只能呼叫常成員函式。
A、通過例子來理解const是函式型別的一部分,在實現部分也要帶該關鍵字。
#include <iostream.h> class A{ private: int w,h; public: int getValue() const; int getValue(); A(int x,int y) { w=x,h=y; } A(){} }; int A::getValue() const //實現部分也帶該關鍵字 { return w*h; //???? } void main() { A const a(3,4); A c(2,6); cout<<a.getValue()<<c.getValue()<<"cctwlTest"; system("pause"); }
B、通過例子來理解const關鍵字的過載
class A{ private: int w,h; public: int getValue() const { return w*h; } int getValue(){ return w+h; } A(int x,int y) { w=x,h=y; } A(){} }; void main() { A const a(3,4); A c(2,6); cout<<a.getValue()<<c.getValue()<<"cctwlTest"; //輸出12和8 system("pause"); }
C、通過例子來理解常成員函式不能更新任何資料成員
class A{ private: int w,h; public: int getValue() const; int getValue(); A(int x,int y) { w=x,h=y; } A(){} }; int A::getValue() const { w=10,h=10;//錯誤,因為常成員函式不能更新任何資料成員 return w*h; } int A::getValue() { w=10,h=10;//可以更新資料成員 return w+h; } void main() { A const a(3,4); A c(2,6); cout<<a.getValue()<<endl<<c.getValue()<<"cctwlTest"; system("pause"); }
D、通過例子來理解
1、常成員函式可以被其他成員函式呼叫。
2、但是不能呼叫其他非常成員函式。
3、可以呼叫其他常成員函式。
class A{
private:
int w,h;
public:
int getValue() const
{
return w*h + getValue2();//錯誤的不能呼叫其他非常成員函式。
}
int getValue2()
{
return w+h+getValue();//正確可以呼叫常成員函式
}
A(int x,int y)
{
w=x,h=y;
}
A(){}
};
void main()
{
A const a(3,4);
A c(2,6);
cout<<a.getValue()<<endl<<c.getValue2()<<"cctwlTest";
system("pause");
}