C++类之const

来源:互联网 发布:新网互联域名登录 编辑:程序博客网 时间:2024/06/10 17:29

因为C++中多了类,那么const也不仅仅局限于修饰普通变量,而且扩展到了类中。
1.const修饰成员数据
const修饰成员数据跟修饰普通变量是一样的,一旦被const修饰,就不能修改。

2.const修饰成员函数
const可以修饰成员函数,首先要知道const所放的的位置,在声明之后,函数体之前,如果声明与定义分开,则不管声明还是定义都要有const。例如:

class A{public:    void display()const;}void A::display()const{}

const修饰的成员函数保证了该函数不能修改类中的数据成员,即也不能调用修改数据成员的非const的成员函数,不修改成员数据的非const成员函数也不能调佣,只能调用const成员函数,说白了就是我不能修改,我调用你,你也不能修改,否则就报错。例如:

class A{private:    int x;public:    void display()const{        print1();    //报错        print2();    //报错        print3();    //正确    }    void print1(){        x = 100;    }    void print2(){    }    void print3()const{    }}

再者const成员函数可以重载,例如:

class A{private:    int x;public:    void display()const{    }    void display(){    }}

这两个display是一种重载,可以同时存在,那何时调用哪个就要看const修饰的第三条:const修饰对象

3.const修饰对象
const修饰对象,是以对象的层面防止成员数据的修改。例如:

class A{private:    int x;public:    void display()const{        cout << "void display()const" << endl;    }    void display(){    cout << "void display()" << endl;    }    void print(){    }}int main(){    const A a;    a.display();   //调用的是void display()const    a.print();    //报错    A b;    b.display();    //调用的是void display()}

const修饰的对象只能调用const成员函数,不能调用非const成员函数,因为要防止成员数据的修改,显然a对象调用的是const修饰的display函数,而非const对象则优先调用非const的display函数,若不存在非const的display函数,则调用const的display。
const类对象同const成员函数一样,都可以访问const和非const的数据成员,但不能修改。

0 0
原创粉丝点击