学习笔记-----关于C++中类的成员函数可以访问私有成员的问题

来源:互联网 发布:淘宝店招尺寸1920 编辑:程序博客网 时间:2024/04/25 20:23

直接上代码吧


template<class T>class vectorList : public linearList<T>{public:vectorList(size_t initCapacity = 10);vectorList(const vectorList<T> & rhs);~vectorList();......protected:void checkIndex(size_t theIndex);vector<T> element;size_t vectorLength;size_t listSize;}


大致就是这样,主要考虑拷贝构造函数vectorList(const vectorList<T> & rhs);该函数的定义如下:

template<class T>vectorList<T>::vectorList(const vectorList<T>& rhs) :element(vector<T>(rhs.vectorLength)),vectorLength(rhs.vectorLength),listSize(rhs.listSize){copy(rhs.element.begin(), rhs.element.end(), element);}



显然,在这个成员函数中rhs直接访问了自身的私有成员vectorLength和listSize


而如果在main.cpp里也这样调用的话就是错的

vectorList<int> vec(2);cout << vec.vectorLength << endl;  错误:编译器会提示没有访问权限


查了一些资料发现

1:与C++机制有关,是C++特殊规定的操作,因为类是设计者自己设计的,设计者完全知道类内部的组成,不需要对设计者隐藏。而使用者即用户不知道类的内部结构,所以分出Public,protected,和private.而且不能再main中调用

2:访问限定符public,protected,private是对其他的类和其他的操作而言的,即如果两个对象属于一个类:上述rhs和*this,在其中一个对象的成员函数中是可以直接调用另一个对象的私有或者保护成员的

3:因为类的接口与封装已经是安全的(对外不可见的),所以在类内部这样使用是不存在不安全问题的

4:如果没有这一机制,则上述拷贝构造函数的初始化就需要在类内增加一些成员函数来返回私有或者保护成员。

0 0
原创粉丝点击