Const

.Declare a variable(常数) to have a constant value.
.Compile time constants.
 .const int bufsize = 1024;
   .value must be initialized
   .unless you make an explicit extern declaration .
  .extern const int bufsize;
   .compiler won’t let you change it.
  .Compile time constants are entries in compiler symbol table, not really variables.
  .数组元素的个数在编译时必须是已知的
   .例:

const int class_size = 12; //Be Known in compile time
int finalGrade[class_size]; //OK

int x;
cin >> x;
const int class_size = x; //OK
double class_Array[class_Array]; //Error! Be known in runing!

.const object [const 对象]
  .例:const Currency the_raise(42, 38); 这样会导致整个类的成员都不能被
   访问,所以可以在成员函数后面加上const进行说明
.const member function useage
 .Repeat the const keyword int the definition as well as the declaration
 .例如:

int get_day() const;
int get_day() const { ... }

.Function members that do not modify data should be declared const
.const member functions are safe for const const objects-实际上说的是"this"
 为 const [1-1.cpp]

#include <iostream>
using namespace std;

class A{
	public:
		A() : i(0) { }
		//overload
		void f() { cout << "A::f()" << endl; } //void f(A* this) { ... }
		void f() const { cout << "A::f() const" << endl; } //void f(const A* this) { ... }
		void set(int ii) { i = ii; }
	private:
		int i;
};

int main()
{
	const A a; //There 'i' must be initialized 
	a.f();
	A aa;
	aa.f();
	aa.set(1);

	return 0;
}

.Constant in class [成员变量为const]- [1-2.cpp]

class A{
	const int i;
};
 //.member variable must be initialized in initializer list of the constructor.

.Compile-time constant in classes

class A{
	const int size;
	int array[size]; //Error!
	...
};
        ||
        ||

class A{
	static const int size = 100;
	int array[size];
	...
};
or
class A{
	enum { size = 100; };
	int array[size];
	...
};

[1-2.cpp]

#include <iostream>
using namespace std;

class A{
	public:
		A() : i(0) { }
		void f() { }
	private:
		const int i; //'i' must be initialized
};

int main()
{
	A a;

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值