常量成员变量及变量成员函数的使用(P121)

/*

    通过常量对象仅可以调用常量成员函数,是因为常量成员函数确保不会修改任何非静态成员变量的值。

    类中定义的const成员变量必须在构造函数的初始化列表中进行初始化。

*/

#include<iostream>
using namespace std;
class constClass
{
const int conMbr;
int Mbr;
public:
constClass():conMbr(0),Mbr(100){}
constClass(int i):conMbr(i)
{
Mbr = 200;
}
void printConst()
{
cout<<"conMbr="<<conMbr<<",Mbr="<<Mbr<<endl;
}
int getConst()
{
cout<<"调用非常量函数"<<endl;
return conMbr;
}
int getConst()const
{
cout<<"调用常量函数"<<endl;
return conMbr;
}
int getValue()
{
return Mbr;
}
void processConst()
{
cout<<"-- 在processConst函数中 非常量 --"<<endl;
int x = 2*conMbr +1;
cout<<"x = 2*conMbr +1"<<x<<endl;
//conMbr++; //错误!不能更改常量成员变量conMbr的值
Mbr++;
cout<<"Mbr="<<Mbr<<endl;
}
void processConst()const
{
cout<<"-- 在processConst函数中 常量 --"<<endl;
int x = conMbr +1;
cout<<"x = conMbr +1"<<x<<endl;
//conMbr++; //错误!不能更改常量成员变量conMbr的值
//Mbr++;
cout<<"Mbr="<<Mbr<<endl;
}
};

int main()
{
constClass ob1(123),ob2;
ob1.printConst();
cout<<"ob2.getConst()="<<ob2.getConst()<<endl;
ob2.processConst();
const constClass ob3(20);
cout<<"ob3.getConst()="<<ob3.getConst()<<endl;
ob3.processConst();
return 0;
}

posted @ 2020-03-07 13:59  CollisionDimension  阅读(304)  评论(0)    收藏  举报