gpt4 book ai didi

c++ - 覆盖另一个类的 friend 的虚拟保护方法

转载 作者:行者123 更新时间:2023-11-28 04:34:23 26 4
gpt4 key购买 nike

基本上,我想以某种方式模拟友元继承,并限制它只能在特定方法内部发生。

所以本质上,这就是我想要的

class A; // Forward declaration
class Base{
friend class A; // friend declaration so that A is able to see protected methods

protected:
virtual void method() {// some definition, might also be pure virtual}

}

class Derived : public Base{
A aObj;
void method(){//override the one in base and also gain access to aObj private members.}
public:
//public interface
}


class A {
int var;
friend void Base::method();
public:
// public interface
}

有什么方法可以做到这一点吗?

最佳答案

这个怎么样

class Base {
friend class A;
protected:
virtual void method() = 0;
std::tuple<int> GetAProperties(const A& a) {
// You can change the tuple params
// as per your requirement.
return std::make_tuple(a.var);
}
}

class Derived : public Base {
A aObj;
void method() override {
auto objProperties = GetAProperties(aObj);
}
}

关于c++ - 覆盖另一个类的 friend 的虚拟保护方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51911563/

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