代码改变世界

C++学习笔记-const和static

2014-11-11 23:11  rangers  阅读(211)  评论(0编辑  收藏  举报

const

1、使用const来定义常量

const int num = 10; //应该在声明时进行初始化,否则该常量的值是不确定的,而且无法修改

2、const与指针

指向常量的指针(const修饰的是指针指向的内容)

//指向常量的指针
double rates[5] = {88.9, 100.12, 59.2, 111.1, 23.2};
const double *pd = rates;
cout << pd[2] << "\n";
pd[2] = 67.99;	//error
cout << pd[2];

pd为指向常量的指针,

 不能使用pd来修改它指向的数值,但可以让pd指向其他的地址。通常把指向常量的指针用作函数参量。

指针常量(const 修饰指针)

//指针常量
double rates[5] = {88.9, 100.12, 59.2, 111.1, 23.2};
cout << pd[2] << "\n";
double * const pd2 = rates;
pd2[2] = 67.99;	//ok
cout << pd[2];

 pd2的值不可改变,只能指向最初赋给它的地址,但pd2可以用来改变它所指向的数据值。

<<effective C++>>上有个好记的方法:const在*号左边修饰的是指针所指的内容;const在*号右边修饰的是指针。
简单记就是:左内容,右指针。
也可以这样理解:先忽略类型名,然后看const离哪个近,就修饰谁。
如:const [int] *p; //先去掉int,这时const 修饰*p, p是指针,*p是指针指向的对象,不可变。

3、const与引用

double value = 100;

const double & v = value;

不能修改const引用所指向的内容

4、const与类成员

class StaticAndConstTest
{
public:
	StaticAndConstTest(int _num = 100);
	~StaticAndConstTest(void);
	//类的const 成员常量 必须在构造方法中使用初始化列表来初始化
	const int num;
};

StaticAndConstTest::StaticAndConstTest(int _num)
	: num(_num)
{
}

 const成员函数

class StaticAndConstTest
{
public:
	StaticAndConstTest(int _num = 100);
	~StaticAndConstTest(void);
	//const成员函数
	void show() const;
	//类的const 成员 必须在构造方法中使用初始化列表来初始化
	const int num;
};

void StaticAndConstTest::show() const
{
	std::cout << num;
}

 const成员函数不能修改调用对象,只要类方法不修改调用对象,就应将其声明为const。

 

static

1、static局部变量

void test()
{
	//static 局部变量 在程序的整个生命周期存在,只有一份,作用域为函数局部
	static int num = 1000;
	num++;
	cout << "num=" << num << "\n";
}
int _tmain(int argc, _TCHAR* argv[])
{
	for (int i = 0; i < 3; i++)
	{
		test();
	}

	return 0;
}

 输出结果:

静态局部变量属于静态存储方式,在函数内定义它的生存期为整个程序生命周期,但是其作用域仍与自动变量相同,只能在定义该变量的函数内使用该变量。
若在声明时未赋以初值,则系统自动赋予0值。而对自动变量不赋初值,则其值是不定的。

2、static全局变量

//静态全局变量 只能在定义它的文件中使用,外部无法访问
static int g_NUM = 100;
非静态全局变量的作用域是整个源程序,也即在各个源文件中都是有效的。

3、static与类

static数据成员与static成员函数函数

class StaticAndConstTest
{
public:
	StaticAndConstTest(int _num = 100);
	~StaticAndConstTest(void);
	//const成员函数
	void show() const;
	//静态成员函数 属于类,
	//无法访问属于类对象的no-static数据成员,也无法访问no-static成员函数,它只能调用其余的静态成员函数。
	static double GetNum();
	//类的const 成员 必须在构造方法中使用初始化列表来初始化
	const int num;
	//类的静态成员变量,属于类,所有类对象共享
	static double NUM_2;
	//静态成员常量
	static const double NUM_3;
	//静态成员是整型const可以在类声明中初始化,其他类型不可以
	static const int NUM_4 = 4;
	
};

//静态全局变量 只能在定义它的文件中使用,外部无法访问
static int g_NUM = 100;
//静态成员变量在类声明中声明,只能在类定义方法的文件中初始化
double StaticAndConstTest::NUM_2 = 100.1;
//静态成员常量 
const double StaticAndConstTest::NUM_3 = 200.1;