【读书笔记】【C++】类外访问私有数据成员的两种方式

来源:互联网 发布:典型plc编程实例 编辑:程序博客网 时间:2024/06/02 03:21

阅读书目

《C++沉思录》——Andrew Koening 、Borbara Moo著,黄晓春 译,孟岩 审校

具体思路

一般思路

设置公有的set和get函数,从而保护数据不会在类外被直接访问

代码如下

#include<iostream>using namespace std; class Vector{public:    Vector() :true_length(0) {}    Vector (int x) :true_length (x){}    int getLength() const    {        return true_length;    }    void setLength (int x)    {        true_length = x;    }private:    int true_length;}; int main(){    Vector x;    x.setLength (5);    cout <<"by getLength:"<<x.getLength() << endl;    return 0;}

结果如下

by getLength:5


另一种思路

添加一个公有的常引用,并将其绑定到相应数据成员上,也可以达到类外访问私有数据成员,但不会修改其值

代码如下

#include<iostream>using namespace std; class Vector{public:    Vector() : length(true_length),true_length(0)  {}    Vector (int x) : length (true_length),true_length (x){}    int getLength() const    {        return true_length;    }    void setLength (int x)    {        true_length = x;    }    const int & length;private:    int true_length;}; int main(){    Vector x;    x.setLength (5);    cout <<"by length:"<<x.length << endl;    cout <<"by getLength:"<<x.getLength() << endl;    return 0;}


 结果如下

 

by length:5by getLength:5

注意事项

在第二个代码中,对length的初始化只能在初始化列表中进行,并且先于true_length的初始化

不然gcc编译会有warning,如下图所示

本人所用gcc版本4.9.2 编译选项有-Wall -fexceptions -g -Wnon-virtual-dtor-Winit-self -std=c++11


 

1 0
原创粉丝点击