如何从其友元类访问抽象类的私有成员?

时间:2014-07-03 13:58:19

标签: c++ abstract-class friend-class

class A  
{  
private:  
        int a,b,c;  
public:
        virtual int get()=0;
         friend class B;
};

class B{
//here I want to access private variables of class A that is a, b and c
};

class C:public class A
{  
        int get(){    
       //some code  
        }  
};

如何在类B中访问类A的私有成员。我不能创建类A的对象,因为它是抽象的。我不得不使用C类的对象来做到这一点但是怎么做?

2 个答案:

答案 0 :(得分:4)

class A {
    friend class B;
private:
    int x;
public:
    A() : x(42) {}
};

class C : public A {
};

class B {
public:
    int reveal_secrets(C &instance){
        // access private member
        return instance.x;
    }

    int reveal_secrets(){
        // access private member of instance created inside B
        C instance;
        return instance.x;
    }
};

void print_secrets(){
    C instance;
    B accessor;
    std::cout << accessor.reveal_secrets(instance) << ", " << accessor.reveal_secrets() << std::endl;
}

答案 1 :(得分:1)

class B拥有以便首先使用实例对象。 实例对象是B为了访问ab而会看到的内容。