您的位置:首页 > 其它

共享数据的包含const

2016-03-23 19:37 316 查看
1、常引用:被引用的对象不能被更新 使用:const 类型名 &引用对象 如const int &a;

2、常对象:必须进行初始化,并且对象不能改变 使用:类名 const 对象名 常对象只能访问常成员函数;

3、常数组:数组元素不能改变 使用:const 数组名

4、常指针:指向常量的指针 const char *p

5、常成员函数:在函数体中不能改变对象的数据成员;使用:void A::f() const{}

注意:const可以参与对重载函数的区分;

常引用做形参:

#include<iostream>
using namespace std;
void display(const double& r);
int main()
{   double d(9.5);
display(d);
return 0;
}
void display(const double& r)
//常引用作形参,在函数中不能更新 r所引用的对象。
{   cout<<r<<endl;   }


常对象:

class A
{
public:
A(int i,int j) {x=i; y=j;}
...
private:
int x,y;
};
A const a(3,4); //a是常对象,不能被更新


常成员函数:

#include<iostream>
using namespace std;
class Cuboid
{
const int length;
const int weight;
const int height;

public:
Cuboid(int i,int k,int j);
int volume() const;//常成员函数,,,,常对象只能访问常成员函数;

};
Cuboid::Cuboid(int i,int k,int j):length(i),weight(j),height(k)
{}

int Cuboid::volume() const
{
return length*weight*height;
}
int main()
{
Cuboid const cu(12,10,12);
cout<<"volume = "<<cu.volume()<<"\n";

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: