简体   繁体   中英

Accessing private members of a private member

I am trying to implement a class Heap using a class DynamicArrayList of mine. In my header file the Heap includes my DynamicArrayList header and has the DynamicArrayList as a private member. In implementing my Heap I want to use the array "data" that is also a private member in my DynamicArrayList , however it gives me the error that:

DynamicArrayList::data cannot access private member declared in class DynamicArrayList

When I try to change the array in the Heap file. For example I would try

lst.data[0] = lst.data[heapSize]

with lst being the DynamicArrayList defined as a private member in the Heap file and I would get the error. Should I change the members from private to protected or what else can I do to access the array?

You should make DynamicArrayList a friend of other objects of the same type. This way you can access private data in methods defined in the class. Friend should be used lightly because it breaks encapsulation.

Here is a link to how use friends : https://www.tutorialspoint.com/cplusplus/cpp_friend_functions.html

Here is another example using templates, since I assume you will be using them for your project based on the class you are defining. example:

template<typename eltType>
class Data {
public:
// add new content
void add(const eltType& _data){
    myStuff.push_back(_data);
}

// append data
void append(const Data<eltType>& _data){
    vector<eltType>::const_iterator it = _data.myStuff.begin();

    for (; it !=  _data.myStuff.end(); it++){
        this->myStuff.push_back(*it);
    }
}

// print data
void print(void){
    vector<eltType>::iterator it = this->myStuff.begin();

    for (;it != this->myStuff.end(); it++){
        printf((*it + "\n").c_str()); 
    }
}

// my friend
friend Data<eltType>;
private:
vector<eltType> myStuff;
};

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM