//const关键字 被const修饰的即表明是常量性的,只读性的 .所以const对象必须初始化
//const 可以修饰变量 函数 指针
#include <iostream>
#include <string.h>
using namespace std;
class Base
{
void function() const //const修饰类成员函数在后边修饰
{ //被const修饰的成员函数不能修改类中任何成员变量,且只能调用其他被const修饰的成员函数
}
};
class Person
{
public:
int age;
const string name; //cosnt修饰的类成员变量,要么在声明时赋值,要么在构造函数前用初始化列表赋值
Person(int age,string name):name(name)
{
this->age = age;
}
void func()const
{
//age = 20; 被const修饰的成员函数不能修改类中任何成员变量,且只能调用其他被const修饰的成员函数
show(); //只能调用其他被const修饰的成员函数
}
void show()const
{
cout<<"show执行"<<endl;
}
};
int main(void)
{
Person person(18,"xiaoming");
person.func();
//修饰变量
const double min = 66;
//min = 99; err: const 修饰的变量的值不能改变
//修饰指针
int i = 10;
int j = 8;
const int *p1 = &i; //p1的const离int近,所以指针所指向的int类型的变量的值不能变,但指针的值能变
//*p1 = 100;
p1 = &j;
int const *p2 = &i; //const离*近,但是const不能修饰*,所以还是修饰的int,所指的值不能变,但是指针能变
//*p2 = 100;
p2 = &j;
int *const p3 = &i; //const离p3近,修饰的是p3,指针所指的值能变,但是指针不能变
*p3 = 100;
//p3 = &j;
const int *const p4 = &i; //两个const分别修饰了int和p4 使指针所指的值和指针都不能变了
return 0;
}
C++关键字-const
最新推荐文章于 2024-05-13 14:11:50 发布