🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## const修饰变量 一般用const完全替代C语言的define,且功能更多。用const修饰变量,使之成为常量(或常数) <details> <summary>main.cpp</summary> ``` #include <iostream> #include <string> using namespace std; typedef const double CONSTANT; CONSTANT PI = 3.141592; struct Person { const string name; int age; }; int main() { cout << PI << endl; // 345 Person p = {"cpj", 123}; // 常量无法修改 // p.name="new_cpj"; p.age = 345; cout << p.age << endl; // 345 return 0; } ``` </details> <br/> ## const修饰类的成员函数 在函数后定义 const,使该函数不能修改成员变量,但可修改非成员变量 <details> <summary>main.cpp</summary> ``` #include <iostream> using namespace std; class A { int x; public: void set(int a) { x = a; } // 在函数后定义 const,使该函数不能修改成员变量 void const_set(int a) const { x = a; } }; int main() { A a; a.set(123); // 编译错误 // a.const_set(132); return 0; } ``` </details> <br/> ## mutable与const为敌 用mutable修饰成员变量,可以使该成员变量即使在const成员函数中也能被修改。 <details> <summary>main.cpp</summary> ``` #include <iostream> using namespace std; class A { mutable int x; public: void set(int a) { x = a; } void const_set(int a) const { x = a; } }; int main() { A a; a.set(123); // 可正常赋值 a.const_set(132); return 0; } ``` </details> <br/>