1. const修饰变量
C++中,const 关键字的作用:如果你不希望某些变量被修改,就可以使用关键字const限定变量,防止变量被修改,被const修饰的变量主要由编译器来实行此约束,例:
const int a = 9;
int b = a; //正确
a = 10; //错误
2.const修饰指针
用const修饰指针有三种情况:
- const修饰指针指向的内容,内容为不可变量。
- const修饰指针,指针为不可变量。
- const修饰指针和内容,都为不可变量。
1.const修饰指针指向的内容
const int *p = 8
指针指向的8为不变量,我们称为左定值。
2.const修饰指针
int q = 8;
int * const p = &q;
*p = 8 //正确
int b= 4
p = &b //错误
3.const修饰指针和指针指向的内容
这是第一和第二中情况的综合
int a = 9;
const int * const p = &a
3.const修饰函数参数和函数返回值
const修饰函数参数
1.值传递的函数参数,一般这种情况不需要 const 修饰,因为函数会自动产生临时变量复制实参值。
#include<iostream>
using namespace std;
void Cpf(const int a)
{
cout<<a;
// ++a; 是错误的,a 不能被改变
}
int main(void)
{
Cpf(8);
system("pause");
return 0;
}
2.const参数为指针,防止指针被修改
void Cpf(int *const a)
{
cout<<*a<<" ";
*a = 9;
}
3.自定义类型的参数传递,需要临时对象复制参数,对于临时对象的构造,需要调用构造函数,比较浪费时间,因此我们采取 const 外加引用传递的方法。
并且对于一般的 int、double 等内置类型,我们不采用引用的传递方式。
#include<iostream>
using namespace std;
class Test{
public:
Test(){}
Test(int _m):_cm(_m){}
int get_cm()const
{
return _cm;
}
private:
int _cm;
};
void Cmf(const Test& _tt) //const外加引用传递
{
cout<<_tt.get_cm();
}
int main(void)
{
Test t(8);
Cmf(t);
system("pause");
return 0;
}
4.const修饰成员变量和成员函数
在类中,如果你不希望某些数据被修改,可以使用const关键字加以限定。const 可以用来修饰成员变量和成员函数。
const成员变量
const 成员变量的用法和普通 const 变量的用法相似,只需要在声明时加上 const 关键字。初始化 const 成员变量只有一种方法,就是通过构造函数的初始化列表。
const成员函数(常成员函数)
const 成员函数可以使用类中的所有成员变量,但是不能修改它们的值,这种措施主要还是为了保护数据而设置的。const 成员函数也称为常成员函数。
常成员函数需要在声明和定义的时候在函数头部的结尾加上 const 关键字。
class Student{
public:
Student(char *name, int age, float score);
void show();
//声明常成员函数
char *getname() const;
int getage() const;
float getscore() const;
private:
char *m_name;
int m_age;
float m_score;
};
Student::Student(char *name, int age, float score): m_name(name), m_age(age), m_score(score){ }
void Student::show(){
cout<<m_name<<"的年龄是"<<m_age<<",成绩是"<<m_score<<endl;
}
//定义常成员函数
char * Student::getname() const{
return m_name;
}
int Student::getage() const{
return m_age;
}
float Student::getscore() const{
return m_score;
}
需要强调的是,必须在成员函数的声明和定义处同时加上 const 关键字。char *getname() const和char *getname()是两个不同的函数原型,如果只在一个地方加 const 会导致声明和定义处的函数原型冲突。
区分const的位置:
- 函数开头的 const 用来修饰函数的返回值,表示返回值是 const 类型,也就是不能被修改,例如const char * getname()。
- 函数头部的结尾加上 const 表示常成员函数,这种函数只能读取成员变量的值,而不能修改成员变量的值,例如char * getname() const。