【发布时间】:2019-01-25 10:49:39
【问题描述】:
基本上,我想以某种方式模拟友谊继承,但它只能在某个方法内部发生。
所以本质上,这就是我想要的
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
}
有没有办法做到这一点?
【问题讨论】:
-
请阅读问题,我对从 A 内部调用
method不感兴趣,我想允许base的派生类从特定方法中访问 A 的私有成员。 -
为什么要设这么多限制?
-
因为我只希望 base 的派生类能够访问 A 的私有成员,而不必每次从 Base 派生时手动将朋友声明插入 A
-
在派生类中,
A成员必须定义为A*以避免non complete class编译器的错误。 -
不确定我是否 100% 了解您在寻找什么,我刚刚发布了一个可能的答案,请不要犹豫,告诉您这不是您要找的。span>
标签: c++ inheritance overriding friend