基本上,我想以某种方式模拟友谊继承,这种限制只能在某种方法内部发生。
所以本质上,这就是我想要的
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
}
反正有实现这一目标的方法吗?
答案 0 :(得分:1)
怎么样
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);
}
}
答案 1 :(得分:0)
您可以在A
中获得指向private的Base
成员的指针,然后将这些成员指针传递给Derived
:
class A; // Forward declaration
class Base{
friend class A; // friend declaration so that A is able to see protected methods
private:
void method(A&);
virtual void do_method(A& a,int A::* var) {// some definition, might also be pure virtual
(a.*var)++;
}
};
class A{
int var;
friend void Base::method(A&);
};
class Derived : public Base{
A aObj;
virtual void do_method(A& a,int A::* var) {// some definition, might also be pure virtual
a.*var+=2;
}
public:
//public interface
};
void Base::method(A& a){
do_method(a,&A::var);
}
注意:不要在关键关卡上使用它!