常函数
常对象
声明对象前加const称该对象为常对象
常对象只能调用常函数
const 类型名 常数据成员名
简单实例 #include <iostream> #include <string> using namespace std;class Person { public : int A_age; mutable int B_age; void showperson () const { cout << "年龄:" << B_age<<endl; } };
void test01 () { Person p; p.B_age = 80 ; p.showperson (); } void test02 () { const Person p; p.B_age = 30 ; p.showperson (); }
int main () { test01 (); test02 (); system ("pause" ); return 0 ; }
课本实例 #include <iostream> #include <string> using namespace std;class Croster { string name; int Math; const double Score; double GPA; public : Croster (string na = "undef" , int m = 100 , double s = 3 ); double GetGPA () const ; void Display () const ; void Display () ; };
#include "l4_07.h" Croster::Croster (string na, int m, double s) :name (na), Math (m), Score (s) { GPA = Math / 100.0 * Score; } double Croster::GetGPA () const { return GPA; } void Croster::Display () { cout << "This is void Display().\n" ; cout << name << "get " << Math << endl; cout << "Your GPA is " << GetGPA () << endl; } void Croster::Display () const { cout << "This is void Display() const.\n" ; cout << name << "get " << Math << endl; cout << "Your GPA is " << GetGPA () << endl; }
#include "l4_07.h" int main () { const Croster stu_A ("赵衍" , 92 , 3 ) ; Croster stu_B ("孙立" ,98 ,3 ) ; stu_A.Display (); stu_B.Display (); return 0 ; }
This is void Display() const. 赵衍get 92 Your GPA is 2.76 This is void Display(). 孙立get 98 Your GPA is 2.94
该程序中的Display()函数有重载的版本,一个是常成员函数,另一个是普通成员函数,函数首部的最后是否有const加以区分。从运行结果可知,同样是调用Display()函数,常对象的调用的一定是常成员函数void Display() const,而普通对象在调用时遵循这样的原则:如果有普通成员函数的重载版本,则首先调用普通成员函数;否则,自动调用常成员函数,因为普通对象也是可以调用常函数的。