const 详解

一、 const:

关键字,限定一个变量不可被修改

二、const的使用

2.1 定义const变量:初始化完成后,值不可被修改

2.2 const和指针

常量指针:不能通过指针修改指针所指向的变量的值。但是指针可以指向别的变量。

指向常量的指针(指针常量):指针常量的值不能被修改,即不能存一个新的地址,不能指向别的变量。但是可以通过指针修改它所指向的变量的值。 

 2.3 const和函数:const在函数中根据修饰位置分三种,

const int fun(const int a)const;
  • 修饰返回值 const int fun();不能修改返回值。

  • 修饰函数形参 int func(const int a);函数体内不能修改形参a的值。

  • 修饰类的成员函数 int func() const函数体内不能修改成员变量的值,增加程序的健壮性或鲁棒性。只有成员函数才可以在后面加const,普通函数后加const无意义。

eg 2.1:const 成员函数

#ifndef Point_h
#define Point_h

#include<iostream>
using namespace std;

class Point
{
public:
	Point(float a=0,float b=0);
	float get_x() const;
	float get_y() const;
	void move(float a,float b);//偏移量
	void print() const;//成员函数

private:
	float x;
	float y;//一个点有x坐标和y坐标
};
#endif  /* Point_h */
#include"Point.h"

Point::Point(float a,float b):x(a),y(b)
{
}

float Point::get_x () const
{
	return x;
}

float Point::get_y () const
{
	return y;
}

//偏移量
void Point::move(float a,float b)
{
	x+=a;
	y+=b;;
}

void Point::print () const
{
	cout<<"("<<x<<","<<y<<")";
}
/* Point.c"

 2.4 const 对象const Point p;

eg 2.1 中加入以下的主函数代码:

#include<iostream>
#include<math.h>
#include"Point.h"
using namespace std;

int main(int argc,const char* argv[])
{
	const Point p;
	p.print();//正确
	//p.move(1,1)//错误
	return 0;
}

总结:

const 对象只能调用const成员函数不能调用普通成员函数;

而普通对象既可以调用const成员函数也可以调用普通成员函数。

 

  • 41
    点赞
  • 184
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值