gpt4 book ai didi

c++ - 如何从友元类访问抽象类的私有(private)成员?

转载 作者:行者123 更新时间:2023-11-30 01:17:21 24 4
gpt4 key购买 nike

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 类的私有(private)成员。我无法创建 A 类的对象,因为它是抽象的。我必须以某种方式使用 C 类的对象来执行此操作,但是该怎么做呢?

最佳答案

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;
}

关于c++ - 如何从友元类访问抽象类的私有(private)成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24555726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com