MichaelBlog

double i = Double.MAX_VALUE; while(i == i + 1){ System.out.print ("学无止境");};

导航

C++: const常量指针,指针常量,常函数,常对象

const常量指针

指向的值不可以改,指针的指向可以修改。
在这里插入图片描述
在这里插入图片描述

const指针常量

指针的指向不可以该,指向的值可以改。
在这里插入图片描述

在这里插入图片描述

const int * const p = &a;

特点:指针的指向和指针的值都不可以改(两个const限定)

#include <iostream>
using namespace std;
int main() {
	//const 修饰指针  常量指针
	int a = 10;
	int b = 10;

	const int* const p = &a;
	/*均不可以修改
	*p = 20; //错误
	 p = &a; //错误
	*/
	system("pause");
	return 0;
}

🎇小提示:const后面跟谁,谁就不可以改。

const修饰成员函数

常函数:
  • 成员函数后加const后称为常函数
  • 常函数内不可以修改成员属性
  • 成员属性声明时加关键字mutable后,在常函数中可以修改
常对象:
  • 声明对象const+对象名。
  • 常对象只能调用常函数。
#include <iostream>
#include <string>

using namespace std;
//空指针调用成员函数
class Person {
public:
    int m_A;
    mutable int m_B; //加mutable可以修改常函数属性
    void showPerson()const 
    {
    //const Person * const this;//与上面常函数一样
    //this指针的本质是指针常量,指针的指向是不可以修改的
    //在成员函数后面加const,修饰的是this指向,让指针指向的值也不可以修改。
        //this->m_A = 100;
        // this = NULL; 
        this->m_B = 100;
    }
    void func()
    {
    }
};
void test1() {
    Person p;
    p.showPerson();
}

void test2() {
   const Person p; //常对象
  // p.m_A = 100;
   p.m_B = 100;//在常对象下也可以修改
   //常对象只能调用常函数
   p.showPerson();
 //  p.func(); //常对象只能调用常函数!
}
int main(){
    test1();
   
    system("pause");
    return 0;

}

posted on 2022-04-16 09:48  Michael_chemic  阅读(39)  评论(0编辑  收藏  举报