C++ const 关键字详解

const 代表常量, 是一个比较常用到的关键字

1.在声明中, 其一般是指一个量拥有固定的值, 无法改动, 且赋值要在声明中

比如:

1 #include <iostream>
2 using namespace std;
3 int main()
4 {
5   const int x=42;//声明一个常量x的值为42
6   cout<<x<<endl;
7   return 0;
8 }

在第六行, 我们输出x的值, 这是完全允许的, 因为 cout 的功能就是输出, 而输出并不会改变该变量的值

如果我们将代码改成这个样子, 就会报错:

1 #include <iostream>
2 using namespace std;
3 int main()
4 {
5   const int x;
6   cin>>x;//或者 x=42;
7   cout<<x<<endl;
8   return 0;
9 }

在第六行 (或注释内容的操作), 我们尝试着去修改x的值 (输入也是一种赋值), 当然会报错

2.在函数中

我们将参数传入函数中, 如果我们不想改变该类的数据成员 (或者是参数)

注意: 只是不想改变, 不是限定传入的参数数据类型必须为const

比如:

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 string HelloName(const string str)
 5 {
 6   return "Hello, "+str+"!\n";
 7 }
 8 int main()
 9 {
10   string name;
11   cin>>name;
12   cout<<HelloName(name);
13   return 0;
14 }

name 不是 const, 但是传入HelloName 后自动在函数内部转换为const, 进行操作

里面的const操作与声明的const变量的规则一致

我们还可以在不修改变量值的函数后加上 "const", 用于类:

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 class PERSON
 5 {
 6 private:
 7   string name;
 8 public:
 9   PERSON(const string str):name(str){}
10   string GetName() const;
11 };
12 string PERSON::GetName() const
13 {
14   return name;
15 }
16 int main()
17 {
18     PERSON person("TweeChalice");
19   cout<<person.GetName()<<endl;
20     return 0;
21 }

我们可以看出, PERSON::GetName() 成员函数没有修改任何值, 因此可以在后缀加上 "const "

注意: 大部分情况下, 后缀拥有 const 的函数不能修改任何值, 除了 mutable 关键字

猜你喜欢

转载自www.cnblogs.com/tweechalice/p/11435802.html