https://www.bilibili.com/video/BV1VJ411M7WR?p=34
const在class中的应用?
常量指针 指针常量
常量引用
#include <iostream>
//const在类中的应用
class Entity{
private:
int m_x,m_y;
mutable int m_z;//即使在const的成员函数中 仍然可以修改
public:
int test;
int GetX() const //这个method不能修改成员变量的值
{
//m_x=10;会报错
m_z=2;//mutable变量不会报错
return m_x;
}
void SetX(int x){
m_x=x;
}
};
void PrintEntity(const Entity&e){//这里跟pointer不一样的是 没有什么内容和所指向内容的区别
//e.test=1;会报错
std::cout<<e.GetX()<<std::endl;//这时候如果删掉GetX后面的const会报错,保证了不会修改e的内容
}
int main(){
int x=1;
const int * a=new int(10) ;//常量指针 指针内容可以改变 但是指针指向的内容不可以改变
//*a=100;会报错
a=&x;//不会报错
std::cout<<*a<<std::endl;
int *const b=new int(20);//指针常量 指针内容不可以改变 但是指针指向的内容可以改变
std::cout<<*b<<std::endl;
*b=13;
std::cout<<*b<<std::endl;
//b=a;会报错
}
|