本文总体是对于const的小结
const声明 可以在类,成员,成员函数,引用之前
1. const 类
声明格式:const 类名 对象名
const A a(3,4);
这里的对象一定要初始化,且不能更新,且只能调用const类型的成员函数。
2.const 成员
声明格式:const 类名 对象名
const int a;
A::A(int i)a(i){} //a 的初始化只能通过构造函数初始化表进行。
static const int b=10;//对于静态常量int ,bool 型可以直接赋值。
3.const 成员函数
声明格式:类型说明符 函数名 (参数表) const;
void print()const
该函数可以被非const 的类调用,但是类调用过程中也将视为const型类,所以该函数不能更新目的对象的数据成员。
4.const 引用
声明格式:const &p;
该引用的引用对象不能被更新,且非const的引用只能绑定普通对象,不能绑定const 对象。
如
1.float dist( point &p1, point &p2)
{
double x= p1.x-p2.x;
double y=p1.y-p2.y;
return x+y;
}
const ponit mp1(4,5),mp2(2,2);
dist(mp1,mp2);// 会报错
----------
2.float dist(const p &p1,const p &p2)
{
double x= p1.x-p2.x;
double y=p1.y-p2.y;
return x+y;
}
const ponit mp1(4,5),mp2(2,2);
dist(mp1,mp2);// 不会报错。
----------
3.float dist(const p &p1,const p &p2)
{
double x= p1.x-p2.x;
double y=p1.y-p2.y;
return x+y;
}
ponit mp1(4,5),mp2(2,2);
dist(mp1,mp2);// 不会报错。