![](/img/trans.png)
[英]How to access a private member in the baseclass from a subclass with inheritance ( C++ )
[英]c++ Getting access to member outside from inheritance chain
我的设计如下:-一个类A具有一个受保护的类M的成员。-一个类B从A继承并具有指向类C的对象的指针-一个类C需要访问其成员A级
class A {
public:
A() : _member(0) {}
~A() { delete _member }
protected:
M _member;
}
class B : public A {
public:
B(){}
~B(){}
protected:
C* c;
}
class C {
// C needs to have access to _member
}
哪种设计应该更适合解决此问题?
让C
成为A
的friend
:
class A {
friend class C;
/*and so on*/
然后C
可以看到所有的成员变量和函数A
,即使是private
。
用纯粹的OO术语来说,允许一个类直接访问另一个类的内部字段是一种不好的做法。
就是说,C ++不是纯OO语言,并且确实允许这种情况(与OO的其他重要区别)。
要允许私人成员访问另一个班级,您必须将该班级指定为好友。 但是,友谊不会传递给派生类,因此您必须将类转换为所需的类型。
这是您最简单的解决方案:
class A {
public:
A() : _member(0) {}
~A() { delete _member }
protected:
friend class C;
M _member;
}
class B : public A {
public:
B(){ c = new C(this); } // this call will cast the B* to an A* (important)
~B(){ delete c;}
protected:
C* c;
}
class C {
public:
C(A* a) { _a->_member = new M(); } //Now C can directly access _member in A
}
以这种方式,任何从A
派生的对象都可以转换回A*
并用于访问_member
。
但是, _member
,由于不继承友谊,所以从C派生的任何类都无法访问_member
,因此需要更全面的解决方案:
class M {
public:
void Foo() { printf("Foo called\n"); }
};
class A {
M* m;
friend class C;
public:
A():m(0) { ; }
};
class B :public A {
int id;
public:
B() { id = 0; }
};
class C {
public:
C() { _a = 0; }
C(A* a) { _a = a; }
protected:
M* getM() { return _a->m; }
void setM(M* m_) { _a->m = m_; }
private:
A* _a;
};
class D : public C {
public:
D(B* b): C(b) {
}
void Foo() {
setM(new M());
getM()->Foo();
delete getM();
setM(nullptr);
}
};
int main()
{
B* b = new B();
D d(b);
d.Foo();
delete b;
getchar();
return 0;
}
这样,没有派生自A的类提供对_member的直接访问,也没有派生自C的类具有直接访问的权限,但仍然可以通过C的受保护API来访问member变量。 这也防止其他外部对象访问它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.