C++之共享数据的保护

共享数据的保护

  1. 对于既需要共享、又需要防止改变的数据应该声明为常类型(用const进行修饰)。
  2. 对于不改变对象状态的成员函数应该声明为常函数。

常类型

  1. 常对象:必须进行初始化,不能被更新。
  2. const 类名 对象名
  3. 用const进行修饰的类成员:常数据成员和常函数成员
  4. 常引用:被引用的对象不能被更新。
  5. 常数组:数组元素不能被更新
  6. 常指针:指向常量的指针

常对象

用const修饰的对象

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

常成员函数

  1. 常成员函数说明格式:
          类型说明符 函数名(参数表)const;
      这里,const是函数类型的一个组成部分,因此在实现部分也要带const关键字

  2. const关键字可以被用于参与对重载函数的区分

  3. 通过常对象只能调用它的常成员函数。

常成员函数举例:

#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(); //调用void print()
  const R b(20,52); 
  b.print(); //调用void print() const

  return 0;

}

结果为:

5:4
20:52

常数据成员举例

#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和b,并以100和0作为初值,分别调用构造函数,

//通过构造函数的初始化列表给对象的常数据成员赋初值

  A a1(100), a2(0);
  a1.print();
  a2.print();

  return 0;
}

结果为:

100:10
0:10

常引用(解决友元函数参数传递提高效率而无法保证数据安全的问题)

  1. 如果在声明引用时用const修饰,被声明的引用就是常引用。
  2. 常引用所引用的对象不能被更新。
  3. 如果用常引用做形参,便不会意外地发生对实参的更改(限制双向传递)。常引用的声明形式: const 类型说明符 &引用名;

常引用做形参举例

#include <iostream>
#include <cmath>
using namespace std;

class Point { //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: ";
	cout << dist(myp1, myp2) << endl;

       return 0;
}

结果为:

The distance is: 5
发布了256 篇原创文章 · 获赞 28 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43283397/article/details/104440564