const在类中,可以修饰成员变量和成员函数,主要目的也是保护成员内部的一些属性不被轻易的修改。以保证数据的完整性。下面分别介绍const修饰成员变量和成员函数。
const修饰成员变量表示成员常量,只能在初始化列表中赋值,可以被const和非const成员函数调用,但不能修改其值。
#pragma once class CConst { public: // 在初始化列表初始化const成员函数 CConst(void):iValue(200) { // error // iValue = 300; } ~CConst(void); private: // const 成员变量 const int iValue; };
const修饰成员函数目的是不让函数修改类内部的数据成员,而且不会调用其他非const成员函数(如果调用则编译出错)
#include <iostream> using namespace std; class CConst { public: // 在初始化列表初始化const成员函数 CConst(void):x(200), y(300){} // const 成员函数中的const修饰符只能在函数名后面 void display() const { // 不能调用非const函数,本函数不修改成员变量,但不能保证被调用函数不会修改 // input(); cout << "x " << x << endl; cout << "y " << y << endl; // const 修饰函数表示承诺不对数据成员进行修改,所以以下错误 //y = 200; } // 一个非 const 成员函数 void display() { y = 200; input(); cout << "x " << x << endl; cout << "y " << y << endl; } void input() { cin >> y; } ~CConst(void); private: const int x; int y; };