一个常引用、静态常变量的例子:
#include <iostream>
using namespace std;
class B{
public:
B(int i):y(i),x(y){ };
static void f() {cout<<"f,B:"<<z<<endl;};
void handler() { cout<<"y:"<<y<<"x:"<<x<<endl; };
const int &x; //公有成员变量
private:
const int y;
static const int z; // static const int z=10;在vc6.0中报错!
};
const int B::z=10; //一定要进行初始化,否则,链接错误。
int main()
{
B b(11);
b.handler();
B::f();
return 0;
}
运行结果:
y:11x:11
f,B:10
常引用、常变量要在构造函数的初始化列表中初始化。如上面所示。