#include <iostream>
using namespace std;
void ValueConst(const int var)
{
//var = 10; //错误 var是常量,不能改var的值;
cout << "var==============" << var << endl;
}
//void PointerContentConst(const int* var) const //错误 “PointerContentConst”: 非成员函数上不允许修饰符
void PointerContentConst(const int* var)
{
int b = 10;
int *a = &b;
cout << "var==" << var << " *var====old=====" << *var << endl;
// *var = b; //错误 var指向的内容不能改变;
var = a; //正确,var指针本身可以修改
cout << "var==" << var << " *var====new=====" << *var << endl;
}
void PointerConst(int* const var)
{
int b = 10;
int *a = &b;
cout << "var==" << var << " *var====old=====" << *var << endl;
*var = b; //正确 var指向的内容可以改变;
//var = a; //错误,var指针本身不可以修改
cout << "var==" << var << " *var====new=====" << *var << endl;
}
//const修改类的成员函数
class Person
{
public:
void eat()
{
PersonVal = 10;
face();
cout << "eat=====================" << endl;
}
void foot() const
{
//PersonVal = 20;//错误 const成员函数不允许修改它所在对象的任何一个数据成员。
//eat(); //错误 const成员函数不能调用非const成员函数。
face();
cout << "foot==============" << endl;
}
void face() const
{
cout << "face==============" << endl;
}
int PersonVal;
};
int main()
{
int nVar1 = 30;
const int nVar2 = 50;
ValueConst(nVar1);
PointerContentConst(&nVar2);
PointerConst(&nVar1);
cout << endl;
Person perA;
perA.eat();
perA.foot();
cout << endl;
const Person perB;
//perB.eat(); //错误 const对象只能访问const成员函数。
perB.foot();
cout << "Hello World!" << endl;
return 0;
}
const用法汇总
最新推荐文章于 2020-09-06 17:03:46 发布