13.1.8 修饰符
修饰符就是对类的成员的限定符,主要有const和mutable两种。const表示不希望类的对象或类的属性在程序运行的过程中被修改,mutable表示总是可以修改。当把一个类声明为const时,它的所有成员属性都将自动成为const型。但有时又需要修改某个const对象中的属性,这时就需要用到mutable修饰符。
【示例13-13】 演示const和mutable的使用方法。
- #include "stdafx.h"
- class A
- {
- int ax;
- mutable int ay;
- public :
- A(int i,int j);
- void show();
- void show() const;
- void modifyY(int y) const;
- };
- A::A(int i,int j)
- {
- ax=i;
- ay=j;
- }
- void A::show()
- {
- cout<<"show()函数调用"<<endl;
- cout<<ax<<endl;
- cout<<ay<<endl;
- }
- void A::show() const
- {
- cout<<"const show()函数调用"<<endl;
- cout<<ax<<endl;
- cout<<ay<<endl;
- }
- void A::modifyY(int y) const
- {
- ay=y;
- }
- void main()
- {
- const A a1(5,10);
- a1.show();
- a1.modifyY(8);
- a1.show();
- A a2(10,15);
- a2.show();
- a2.modifyY(30);
- a2.show();
- }
分析:在上面程序中,在类A中声明了两个show()函数。根据创建对象的不同,系统会自动选择调用不同的函数。当调用了const a1对象的show()函数时,系统自动选择const成员函数。当调用非const a2对象时,系统自动选择非const成员函数。由于a1被定义为const型,因此必须将ay声明为mutable的,否则调用modifyY函数修改ay的值时将会报错,而调用a2的modify函数时,则不会。因此,该示例的输出结果如下所示。
- const show()函数调用
- 5
- 10
- const show()函数调用
- 5
- 8
- show()函数调用
- 10
- 15
- show()函数调用
- 10
- 30
【责任编辑:
云霞 TEL:(010)68476606】