C++各种类型常量

常对象

class c{
public:
	c(int i,int j){
		x = i;
		y = j;
	}
	private:
		int x,y;
};
c const b(1,2); //无法更新常对象b

常成员函数

  • 使用const关键字说明的函数;
  • 不更新对象的数据成员;
  • const关键字可以被用于参与对重载函数的区分;
  • 通过常对象只能调用其常成员函数;
#include <iostream>
using namespace std;
class R{
public:
	R(int r1,int r2):r1(r1),r2(r2){}
	void print();
	void print() const;
private:
	int r1,r2;
};
void R::print(){
	cout << r1 << ";" << r2 << endl;
}
void R::print() const{
	cout << r1 << ";" << r2 << endl;
}
int main(){
	R a(1,2);
	a.print();
	const R b(3,4);
	b.print();//调用的是常成员函数
	return 0;
}


常数据成员

class A{
	public:
		A(int i):a(i){}
		void print();
	private:
		const int a;
		static const int b;
};
void A::print(){
	cout << a << "-" << b << endl;
}
const int A :: b = 10;
int main(){
	A j(1);
	j.print();
	A k(2);
	k.print();
	return 0;
}

常引用

  • 用const声明的引用;
  • 常引用引用的对象不能被更新;
  • 以常引用作为形参不会意外的发生对实参的更改;
int f(const xx &p){...}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值