空指针访问成员函数

class Person(){
public:
	void func1(){
    	cout<<"yes";
    }
    void func2(){
    	cout<<age;//相当于this->age
    }
    int age;
}

int main(){
	Person p=NULL;
    p.func1();//ok
    p.func2();//报错,因为this==NULL,没有age值可以访问
}

const修饰成员函数

  1. 常函数:
  • 成员函数加const以后为常函数

  • 常函数内不可以修改成员属性

  • 如果要修改成员属性,需要在声明时加上mutable

  1. 常对象
  • 声明对象前加上const

  • 常对象只能调用常函数

      class Person{
      public:
      void show() const
      {
      	  age=100;//报错,表达式必须是可修改的左值
          height=180;//不报错
      }
      int age;
      //this指针的本质是常量指针,指针的指向是不可以修改的
      //在成员函数后面加上const相当于:const Person *const this
      //让指针指向的值也不可以修改了
      mutable int height;//特殊变量,在常函数中也可以修改
      
      void fun(){
      	cout<<"hhh";
      }
      };
      
      
      int main(){
      	const Person p;//常对象
          p.age=100;//报错
          p.height=100;//ok
          
          p.show();//ok
          p.func();//报错,常对象不可以调用非 常函数,因为普通成员函数是可以修改属性
      }