c/c++语言开发共享详解C++ 共享数据保护机制

下面随笔说明c++共享数据保护机制。共享数据的保护  对于既需要共享、又需要防止改变的数据应该声明为常类型(用const进行修饰)。  对于不改变对象状态的成员函数应该声明为常函数。(1)常类型  ①

  下面随笔说明c++共享数据保护机制。

共享数据的保护

  对于既需要共享、又需要防止改变的数据应该声明为常类型(用const进行修饰)。

  对于不改变对象状态的成员函数应该声明为常函数。

(1)常类型

  ①常对象:必须进行初始化,不能被更新。

  const 类名 对象名

  ②常成员

  用const进行修饰的类成员:常数据成员和常函数成员

  ③常引用:被引用的对象不能被更新。

  const  类型说明符  &引用名

  ④常数组:数组元素不能被更新(详见第6章)。

  类型说明符  const  数组名[大小]…

  ⑤常指针:指向常量的指针(详见第6章)。

(2)常对象

  用const修饰的对象

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

(3)常成员

  用const修饰的对象成员

  ①常成员函数

  使用const关键字说明的函数。

  常成员函数不更新对象的数据成员。

  常成员函数说明格式:

  类型说明符  函数名(参数表)const;

  这里,const是函数类型的一个组成部分,因此在实现部分也要带const关键字。

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

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

  ②常数据成员

  使用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(); //调用void print()     const r b(20,52);     b.print(); //调用void print() const      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和b,并以100和0作为初值,分别调用构造函数,    //通过构造函数的初始化列表给对象的常数据成员赋初值     a a1(100), a2(0);     a1.print();     a2.print();     return 0;    }

(4)常引用

  如果在声明引用时用const修饰,被声明的引用就是常引用。

  常引用所引用的对象不能被更新。

  如果用常引用做形参,便不会意外地发生对实参的更改。常引用的声明形式如下:

  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;    }

以上就是详解c++ 共享数据保护机制的详细内容,更多关于c++ 共享数据保护机制的资料请关注<计算机技术网(www.ctvol.com)!!>其它相关文章!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/596058.html

(0)
上一篇 2021年5月8日
下一篇 2021年5月8日

精彩推荐