主要有两种,一个针对变量,一个针对类
1.对于变量
- const int* a = new int; const意味着指针a的内容无法别改变
- int* const b = new int; const意味着无法改变指针,但可以改变指针指向的内容
- const int* const d = new int;// 既无法改变指针,也无法改变指针的内容
2.对于类
int GetX() const {// const意味着承诺不会修改实际的实体类
// m_X = 2; // 这里m_X无法被修改,const意味着这个类是只读的
return m_X;
}
假如有一个函数PrintEntity如下,const Entity& e意味着不改变这个类,那么如果调用int GetY() { return m_Y; }
将会报错,即使这里并没有改变m_Y的值,因此对于GetY这个函数一般写两个定义GetY
void PrintEntity(const Entity& e) {// 我不想复制我的实体类
//因为const Entity& e,他不能确定GetY是否修改了实体,所以必须GetY后面加上const
// std::cout << e.GetY() << std::endl;
std::cout << e.GetX() << std::endl;
}
代码片段如下:
#include <iostream>
#include "Log.h"
class Entity {
private:
int m_X, m_Y;
int* m_Z;
public:
int GetX() const {// const意味着承诺不会修改实际的实体类
// m_X = 2; // 这里m_X无法被修改,const意味着这个类是只读的
return m_X;
}
int GetY() {
return m_Y;
}
//为了避免PrintEntity函数中的情况,通常会有两个版本的Get函数
int GetY() const {
return m_Y;
}
const int* const GetZ() const{// 不修改指针,不修改指针的内容,不修改实际的实体类
return m_Z;
}
void SetX(int x) {
m_X = x;
}
};
//void PrintEntity(const Entity& e) {// 我不想复制我的实体类
// std::cout << e.GetX() << std::endl;
//}
void PrintEntity(const Entity& e) {// 我不想复制我的实体类
//因为const Entity& e,他不能确定GetY是否修改了实体,所以必须GetY后面加上const
// std::cout << e.GetY() << std::endl;
std::cout << e.GetX() << std::endl;
}
int main() {
Entity e;
const int MAX_AGE = 90;
const int* a = new int; // const意味着指针a的内容无法别改变
// 1
// *a = 2; // 这里会发现报错
a = (int*)&MAX_AGE; // 这里是指针a的地址被改变,但是没有直接更改指针指向的内容,所有没报错吗
std::cout << *a << std::endl;
// 2. const
int* const b = new int;//无法改变指针,但可以改变指针指向的内容
const int* c = new int;//此处调换两者的位置是相同的作用
// b = &MAX_AGE;// 这里会发现报错
// b = (int*)&MAX_AGE;
// b = nullptr;
*b = 3;
// 3.
const int* const d = new int;// 既无法改变指针,也无法改变指针的内容
std::cout << "hello" << std::endl;
}