8.3 传递和返回地址
事实上,无论什么时候传递一个地址给一个函数,都应该尽可能用const修饰它。如果不这么样做,就不能以const指针参数的方式使用这个函数。
看下面的例子:
// const_reference.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" void t(int*) { } void u(const int* cip) { //*cip = 2; *cip can't be modified int i = *cip; //int* ip2 = cip; non-const } const char* v() { return "result of function v()"; } const int* const w() { static int i; return &i; } int _tmain(int argc, _TCHAR* argv[]) { int x = 0; int* ip = &x; const int* cip = &x; t(ip); // t(cip); can't be const int* u(ip); u(cip); //char* cp = v(); return const char* const char* ccp = v(); //int* ip2 =w(); return const int* const int* const ccip = w(); const int* cip2 = w(); //*w() = 1; *w() is const, can't be modified return 0; }
2、static const
static 无论一个类被创建多少次,都只有一个实例。
类中的一个常量成员,在该类中的所有对象中它都是一样的。因此,一个内部类型的static const 可以看做一个编译期间的常量。
注意:必须在static const 定义的地方对它进行初始化。