c++中const修饰类及其成员小结

来源:互联网 发布:网络上不受欢迎的行为 编辑:程序博客网 时间:2024/06/01 01:34

1、const修饰类的成员变量。

const修饰类的成员变量,表示成员常量,不能被修改,同时它只能在初始化参数列表中赋值(C11支持类中初始化)。可被const和非const成员函数调用,而不可以修改。
class A{public:    A():iValue(521){}private:    const int iValue;}

2、const修饰类的成员函数。

1、const修饰函数的意义:承诺在本函数内部不会修改类内的数据成员,不会调用其他的非const成员函数。其从函数层面上不修改数据。2、const修饰函数的位置:const关键字放在声明之后,实现体之前。
class A {public:    A():x(521),y(125){}    void dis() const    //const对象调用时,优先调用    {        cout<<"x="<<x<<endl;        cout<<"y="<<y<<endl;        //y = 521;     const修饰函数表示承诺不对数据成员修改        //input();     const修饰函数不能调用非const函数    }    void dis()          //构成函数重载,非const到对象时,优先调用    {        y = 521;           input();        cout<<"x="<<x<<endl;        cout<<"y="<<y<<endl;    }    void input()    {        cin>>y;    }private:    const int x;    int y;}

3、const修饰类的对象。

const修饰类对象表示常对象,其在对象层面上承诺不修改数据。
const A a;a.dis();

总结:
1、如果const构成了函数重载,const对象只能调用const函数,非const对象优先调用非const函数。
2、const函数只能调用const函数。非const函数可以调用const函数。
3、类体外定义的const成员函数,在定义和声明处都需要const修饰符。
4、const对象只能调用const函数,但可以访问非const和const数据成员,但不能修改。

1 0
原创粉丝点击