常成员函数,声明方式:类型标识符 函数名(形参列表)const
类的成员函数的一种类型,由于const是函数类型,故在函数实现的时候也应带上const关键字。常成员函数具有以下特殊性质
- 不能更新成员变量的值(静态成员变量除外)
- 不能调用除了常成员函数以外的成员函数
- 可以用来区分函数重载
- 类的常对象只能访问类的常成员函数
class A{
private:
int w, h;
public:
int getValue()const;
int getValue();
A(int x, int y):w(x), h(y){}
A(){}
~A(){}
};
int A::getValue()const{
return w*h;
}
int A::getValue(){
return w+h;
}
int main()
{
const A a(1, 2);
A c(1,2);
cout << a.getValue() << endl; //调用const成员函数
cout << c.getValue() << endl; //调用非const成员函数
return 0;
}
静态成员函数 ,声明方式:static 类型标识符 函数名(形参列表)
静态成员函数只能被定义一次,由类的全体对象共用,属于类的行为,与具体对象无关,而本身也具有如下的特殊性质
- 不可以直接访问类中的非静态成员变量和非静态成员函数,只能通过形参传入的对象名来进行访问。
- 不可以 在函数实现时加static关键词,否则会出错
- 静态成员函数不含this指针,可以在类外通过“类名::函数名”的方式直接调用。也可以通过对象调用
- class B{
- private:
- int x;
- int y;
- static int count;
- public:
- B():x(0), y(0){
- count++;
- }
- B(int xx, int yy):x(xx), y(yy){
- count++;
- }
- static int getObjCount();
- };
- int B::count = 0;
- int B::getObjCount(){
- return count;
- }
- int main()
- {
- cout << B::getObjCount() << endl;
- B b1;
- B b2(10, 20);
- cout << b1.getObjCount() << endl;
- cout << b2.getObjCount() << endl;
- cout << B::getObjCount() << endl;
- return 0;
- }