简体   繁体   中英

how to access private members of one class to another

In the code below, there two classes a and b. The error that i am unable to resolve is that i can't access name and time in class b using pointer ptr of type a. I know that there are other ways to access them using getters or making a friend function however this is the part of my assignment so i am instructed to do it this way. For convenience, I have commented the line that is showing error. It would be a great help if someone helps me to resolve this issue.

class a{
private:
    char name[12];
    char time[12];
public:
    a(){
        strcpy(name,"");
        strcpy(time,"");
    }
    void set(char *n,char *t){
        for(int i=0;n[i]!='\0' && i<12;i++){
            name[i] = n[i];
        
        }
        for(int i=0;n[i]!='\0' && i<12;i++){
            time[i] = t[i];
        
        }
    
    }
    
};


class b{
private:
    a *ptr;
    static int index;
public:
    b(){
        ptr= new a[2];
    }
    b(int size){
        index=size;
        ptr = new a[index];
    
    }
    void show(){
        for(int i=0;i<index;i++){
            cout << ptr[i].name << ", " << ptr[i].time << endl; // Error
            
        }
    }
};

Private members can only be accessed in its class or with getters.
Also, you can make these members protected or public to access them successfully.

You can check this reference for more understanding.

Well since both fields are private in A you can't access them without getters in this case or making them public As pointed out by the comment you can have B inherit form A if the fields are protected

Two solutions for foreign classes where you can't edit the original A class:

A) use pointer arithmetic to access private variable: Create a dynamic object of A and shift the pointer to the offset of the private variable's address, then read the appropriate size.

B) implement a class similar to A with the getters at the end: Create a class (A1) with exactly the same implementation, but add the getters to the end. Then create a dynamic object of A and cast it to A1.

A a;
A1* a1 = reinterpret_cast<A1*>(&a);

Then you can use the getters to access the original A private variables.

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