十九、C++复习——const用法总结
1 const修饰变量
语法:
const 数据类型 常量名 = 常量值
/* 例如: const int month = 12; */
2 const修饰指针
2.1 常量指针
const修饰指针(常量指针):const修饰的是指针,指针指向可以改,指针指向的值不可以更改
const int * p1 = &a;
p1 = &b; //正确
//*p1 = 100; 报错
2.2 指针常量
const修饰常量(指针常量):const修饰的是常量,指针指向不可以改,指针指向的值可以更改
int * const p2 = &a;
//p2 = &b; //错误
*p2 = 100; //正确
2.3 既修饰指针,又修饰常量
cosnt既修饰指针,又修饰常量:
const int * const p3 = &a;
//p3 = &b; //错误
//*p3 = 100; //错误
3 const修饰函数形参
在函数形参列表中,可以加const修饰形参(也叫常量引用修饰形参),防止形参改变实参。
/* 引用使用的场景,通常用来修饰形参 */
void showValue(const int& v) {
//v += 10; /* 无法修改(因为引用v是指针常量,再加const,即修饰指针又修饰常量 */
cout << v << endl;
}
int main() {
//int& ref = 10; 引用本身需要一个合法的内存空间,因此这行错误。正确:int temp = 10; int& ref = temp;
//加入const就可以了,编译器优化代码,int temp = 10; const int& ref = temp;
const int& ref = 10;
//ref = 100; //加入const后不可以修改变量
cout << ref << endl;
//函数中利用常量引用防止误操作修改实参
int a = 10;
showValue(a);
system("pause");
return 0;
}
4 cosnt修饰函数结构体形参
作用:用const来防止误操作
//学生结构体定义
struct student
{
//成员列表
string name; //姓名
int age; //年龄
int score; //分数
};
//const使用场景
void printStudent(const student *stu) //加const防止函数体中的误操作
{
//stu->age = 100; //操作失败,因为加了const修饰
cout << "姓名:" << stu->name << " 年龄:" << stu->age << " 分数:" << stu->score << endl;
}
int main() {
student stu = { "张三", 18, 100 };
printStudent(&stu);
system("pause");
return 0;
}
5 const修饰函数返回值
5.1 返回值是常量
这种情况下,使用const
修饰返回值通常没有太大意义。因为基本类型的返回值通常是按值返回,即返回的是一个副本。修改这个副本并不会影响原始值。
const int getValue() {
return 5;
}
5.2 返回值是引用
当函数返回对象或复合类型(如自定义类、结构体等)时,使用 const 修饰返回值可以防止返回的对象或复合类型被修改。这是一种常见且有用的做法,特别是在返回类的成员变量时。
/* const在函数后面,表示常函数,常函数不可用修改成员属性 */
const MyClass& getClass() const {
return myObject;
}
getClass 函数返回 MyClass 类型对象的常量引用。这意味着调用者可以读取返回的对象,但不能修改它。这种做法既保证了数据的安全性,又避免了不必要的复制。
class MyClass {
private:
int value;
public:
const int& getValue() const {
return value;
}
};
// 在使用时
MyClass obj;
int a = obj.getValue(); // a 不是 const
// obj.getValue() = 10; // 错误,不能通过 const 引用修改值
6 const修饰成员函数:常函数
-
成员函数后加const后我们称为这个函数为常函数
-
常函数内不可以修改成员属性
-
成员属性声明时加关键字mutable后,在常函数中依然可以修改
class Person { public: void ShowPerson() const { this->m_B = 100; } };
7 const修饰类对象:常对象
-
声明对象前加const称该对象为常对象
-
常对象只能调用常函数
class Person {
public:
Person() {
m_A = 0;
m_B = 0;
}
//this指针的本质是一个指针常量,指针的指向不可修改
//如果想让指针指向的值也不可以修改,需要声明常函数
void ShowPerson() const {
//const Type* const pointer;
//this = NULL; //不能修改指针的指向 Person* const this;
//this->mA = 100; //但是this指针指向的对象的数据是可以修改的
//const修饰成员函数,表示指针指向的内存空间的数据不能修改,除了mutable修饰的变量
this->m_B = 100;
}
void MyFunc() const {
//mA = 10000;
}
public:
int m_A;
mutable int m_B; //可修改 可变的
};
//const修饰对象 常对象
void test01() {
const Person person; //常量对象
cout << person.m_A << endl;
//person.mA = 100; //常对象不能修改成员变量的值,但是可以访问
person.m_B = 100; //但是常对象可以修改mutable修饰成员变量
//常对象访问成员函数
person.MyFunc(); //常对象不能调用const的函数
}
int main() {
test01();
system("pause");
return 0;
}