C++类的常成员函数以及静态成员函数

来源:互联网 发布:淘宝售后客服用语 编辑:程序博客网 时间:2024/05/28 05:14

1 常成员函数

1.1声明:<类型标识符>函数名(形参列表)const;

1.2说明:

1)const是函数类型的一部分,在实现部分也要带上该关键字;

2)const关键字可以用于对重载函数的区分;

3)常成员函数不能更新类的成员变量,也不可以调用类中没有用const修饰的成员函数,只能调用常成员函数,但是可以被其他成员函数调用;

4)特别地:常对象只能访问类中const成员函数(除了系统自动调用的隐含构造函数以及析构函数)

1.3例程:

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;}

2 静态成员函数

使用static修饰的成员函数,只能被定义一次,而且要被同类的所有对象所共享,它是类的一种行为,与对象无关,它有如下特点:

1)静态函数成员不可以直接访问类中非静态数据成员以及非静态成员函数,只能通过对象名(由参数传入)来访问;

2)静态成员函数在类外实现时,无需加static修饰,否则出错;

3)在类外,可以通过对象名以及类名来调用类的静态成员函数。

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;}



0 0
原创粉丝点击