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

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



  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值