类中的静态static和常量const的使用

const与类

  1. 成员函数带有const之后就不能对类中的成员进行改变
  2. const对象只能访问const成员函数,非const对象可以访问任何函数,const对象里面的所有成员都不能改变,然而只有const成员函数不会对对象中的成员进行改变,所以const对象为了不改变其成员只能调用const函数
  3. const成员初始化需要在初始化列表中进行
#include<iostream>

using namespace std;

class const_class
{
public :
    int a,b,c,d;
    const int e;
    const_class (int a,int b,int c,int d,int ee = 10):a(a),b(b),c(c),d(d),e(ee){  //只能在初始化列表中进行初始化
        // this->e = 100;
    }
    int f() const{
        return a+b+c+d;
    }
    int g() {
        a = a*2;
        return a+b+c+d;
    }

};

int main()
{
    const const_class cc = {1, 2, 4, 3};
    // cc.a = 10;       //报错!
    cout<<"cc.f() = "<<cc.f()<<endl;
    cout<<"e = "<<cc.e<<endl;
    // cout<<cc.g()<<endl;  //报错!
    const_class dd = {2,3,4,5};     // 列表初始化
    dd.a = 100;
    cout<<"dd.f() = "<<dd.f()<<endl;
    cout<<"dd.g() = "<<dd.g()<<endl;  
    return 0;
}

static与类

  1. 静态对象和静态的变量一样,声明周期为程序结束,结束之后调用析构函数。
  2. 一般使用类名::静态成员使用静态成员。当然对象.静态成员也可以
  3. 静态函数只能访问静态成员或者函数。(为了安全,访问非静态的成员,可能会因为对象不存在而出现问题)
#include<iostream>
using namespace std;

class static_member
{
public:
    static int stat_mem;
    int xx;
    static_member(int xx):xx(xx){}
    int f(){
        return xx + stat_mem;
    }
    static int g(){
        // return xx + stat_mem;       //报错 
        return stat_mem;
    }
};

int static_member::stat_mem = 100;
int main()
{
    static_member aa(10);
    aa.stat_mem = 200;
    cout<<static_member::stat_mem<<endl;
    cout<<aa.stat_mem<<endl;
    cout<<static_member::g()<<endl;
    cout<<aa.f()<<endl;
    return 0;
}
  1. 静态成员的初始化方式不能使用构造函数,因为构造函数会多次初始化这个静态变量。正确的方式是在类外面初始化,就像下面写的
#include<iostream>
using namespace std;

class static_member
{
    public:
    static int stat_mem;
};

int static_member::stat_mem = 10;   //不会报错

int main()
{
    // static_member::stat_mem = 10;   // 报错
    // int static_member::stat_mem = 10;   // 还是报错

    cout<<static_member::stat_mem<<endl;
    return 0;
}

另一种是



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值