1、常引用:所引用的对象不能更新
const 类型说明符 &引用名;
#include <iostream.h>
void display(const double& r);
int main(void){
double d(9.5);
display(d);
return 0;
}
void display(const double& r){
/*
r = 10;
error C2166: l-value specifies const object
*/
//常饮用做形参,函数中不能更新r所引用的对象
cout<<r<<endl;
}
2、常对象:必须进行初始化,而且不能被更新
类名 const 对象名;
#include <stdlib.h>
using namespace std;
class A{
public:
A(int i, int j){x=i;y=j;}
void setX(int x){x=x;}
void setX(int x) const {x=x;}
private:
int x,y;
};
int main(int argc, char *argv[])
{
int const n=10;
//a是常对象,不能被更新
A const a(3,4);
/*
a.setX(5);
'const A' as 'this argument of 'void A::setX(int)' discards qualifiers
*/
system("PAUSE");
return 0;
}
3、常成员函数
类型说明符 函数名(参数表) const;
常对象可以调用常成员函数
4、常数据成员
构造函数对数据成员进行初始化;静态常数据成员在类外说明和初始化
#include <iostream>
#include <stdlib.h>
using namespace std;
class A{
public:
A(int i);
void print();
const int& r;
private:
const int a;
static const int b;
};
const int A::b=10;
A::A(int i):a(i),r(a){
}
void A::print(){
cout<<a<<":"<<b<<":"<<r<<endl;
}
int main(int argc, char *argv[])
{
A a1(100);
a1.print();
system("PAUSE");
return 0;
}