gpt4 book ai didi

c++ - 友元: many classes from same parent

转载 作者:行者123 更新时间:2023-11-28 00:57:40 27 4
gpt4 key购买 nike

如何在所有派生类中没有 friend 的情况下访问 privateMember

class parent{...};  //a virtual class

class A: public parent{...};
class B: public parent{...};
class C: public parent{...};
class D: public parent{...};
class E: public parent{...};
...
//each has a function, that want access to privateMember

class MyClass{
int privateMember;

friend parent;
//I know it doesnt't work, but this shows the best what I want
}

最佳答案

保持原样(使用friend class parent)并向parent添加一个访问器函数,AB,...将使用。它会受到保护,因此层次结构外部的函数无法使用它。

class parent {
protected:
static int& getPrivate( MyClass & c ) { return c.privateMember; }
...
};

你必须这样做,因为友元不会扩展到派生类。

关于c++ - 友元: many classes from same parent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10213682/

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