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类的对象来做到这一点但是怎么做?
答案 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
为了访问a
,b
,等而会看到的内容。