# 共享数据的保护

## 常对象

class A
{
public:
A(int x,int y):x(i),y(j){}

private:
int x,y;

}
const A a(3,4);


## 用const修饰的类成员

### 常成员函数

void print();
void print() const;


#include<iostream>
using namespace std;

class R{

public:
R(int r1, int r2) :r1(r1), r2(r2){ };
void print();
void print() const;
private:
int r1, r2;
};
void R::print(){

cout << r1 << ":" << r2 << endl;
}

void R::print() const{

cout << r1 << ":" << r2 << endl;
}
int main()
{
R a(5, 4);
a.print();
const R b(8, 10);
b.print();
return 0;

}



### 常数据成员

#include<iostream>
using namespace std;

class A{

public:
A(int i);
void print() ;
private:
const int a;
static const int b;
};
const int A::b = 10;//给静态常数据成员赋值

A::A(int i) :a(i){} // 构造函数

void A::print(){

cout << a << ":" << b<< endl;
}

int main()
{
A a1(100),a2(0);//给常数据成员赋值
a1.print();
a2.print();

return 0;

}



### 常引用

const 类型说明符 &引用名；

#include<iostream>
using namespace std;

class Point{

public:
Point(int x = 0, int y = 0) :x(x), y(y){}
int getx(){ return x; }
int gety(){ return y; }
friend  float dist(const Point &p1, const Point &p2);//常对象引用
private:
int x, y;
};
//常对象引用作形参
float dist(const Point &p1, const Point &p2){
double x = p1.x - p2.x;
double y = p1.y - p2.y;

return static_cast<float>(sqrt(x*x + y*y));

}

int main()
{
const Point myp1(1, 1), myp2(4, 5);
cout << "The distance is:" << endl;
cout << dist(myp1, myp2) << endl;

return 0;

}



posted @ 2019-09-29 17:33  znlovewxl  阅读(179)  评论(0编辑  收藏  举报