const_详解

.h

#pragma once
//本头文件用来学习const用法  使用const的常见原因:提高效率

#include <iostream>
using namespace std;

//1,const修饰成员变量

void ConstDemo1()
{
	int num1 = 210;
	const int num2 = num1;
	//num2=100;错误,const不能再改动
	cout << num2 << endl;
	

//const修饰指针变量,指向可以修改,内容不可以修改


//  (1)const在*左边,即数据是常量

	const int* ptr1_num1 = &num1;
	int const * ptr2_num1=&num1; //都可以

	ptr1_num1 = &num2;//合法,地址可以改变
	//*ptr_num1 = 1021 不合法,指针的值不可以改变


//	(2)const在*右侧,即指针本身是常量,不能指向其他内存单元,而数据可以修改

	int* const ptr3_num1 = &num1;
	//ptr3_num1 = ptr2_num1;不合法
	*ptr3_num1 = 299; //可以
	cout << *ptr3_num1 << endl;


//	(3)有两个const位于*两侧,则指针和其指向数据都不能修改
	const int* const ptr4_num1 = &num1;
}

//2.const 修饰函数 --- 函数不会修改成员变量的值

class Test2
{
public:
	int val;
	void modify() { val = 111; }  //void modify()const {val = 111;} 就不行,因为加了const就是不能修改成员变量的值

};

//3.const 修饰函数参数

//	(1)参数是普通变量
void ConstDemo2(const int num) //函数参数num在函数体内不可以改变
{

	//num = 123; 报错
}

//	(2)参数是类型
class Test1
{
private:
	int m_eg;
public:
	Test1(int eg) { m_eg = eg; }
	void seteg(int eg) { m_eg = eg; }
	int geteg()const{ return m_eg; } 
	void choose(int eg){}
	void choose2() const {}
};
void ConstDemo3(const Test1 &test)
{
	//test.choose(123); 错误,因为参数是const 不允许修改Test1引用里面的任何成员,即使choose函数里啥都没有都不行

	//const成员函数不可以调用非const成员函数
	test.choose2();//可以编译,因为void choose2() const {}

	//好处是可以保护传递的参数,不需要一个新的参数副本,节省效率
	//引用传递

}

//4. const修饰返回值   
//返回对象,返回对象引用更有效率

const Test1& Getmax(const Test1& eg1, const Test1& eg2)
{
	if (eg1.geteg() > eg2.geteg())//直接写就是错的,因为是const 所以前面的geteg函数需要加const  int geteg()const{ return m_eg; } 
	{
		return eg1;//这里返回的是引用。 如果不用const 传递回去的就是副本
	}
	return eg2;
}
//在可以返回对象和引用的情况下,首选引用,因为效率高


//如果情况为函数返回局部对象,就应该返回对象,而不要返回对象引用
//返回对象引用是什么意思?
//就是用Test1 eg3,再用eg3来承接要返回的eg2
//此时就应该是 const Test1 Getmax(const Test1& eg1, const Test1& eg2)
//                        ↑注意这里的引用没了


.cpp

#include <iostream>
#include "constdemo.h"
using namespace std;
void Test();
int main()
{
	ConstDemo1();
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值