簡述:
本文介紹一個類裡調用其兄弟類(繼承同一父類)的接口, 但是不直接傳遞兄弟類的實例給調用類實例.
場景:
B和C繼承自A, C通過其父類A調用B的接口操作B的sum.
<喎?http://www.Bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+1K3A7To8YnI+CjwvcD4KPHA+wPvTw0NsYXNzIEEgtcS+ssysseTBvyjBtLHtKSwgtOa0osv509DG5NfTwOAo1eLA77zZyejKx0IptcTKtcD91rjV6ywgzazKsbzHwrzX08DgwODQzSwg1eLR+Swgy/nT0NfTwOAo1eLA77zZyejKx0Mptry/ydLUzai5/bi4wODAtLX308PG5Mv719PA4Ci78s2swOAptcTKtcD9LjwvcD4KPHA+PGJyPgo8L3A+CjxwPrT6wus6PC9wPgo8cD48cHJlIGNsYXNzPQ=="brush:java;">#ifndef A_H
#define A_H
enum NodeType
{
T_A = 0,
T_B = 1,
T_C = 2,
T_Count
};
struct ChildrenNode
{
void* p;
int type;
};
class A
{
public:
A();
~A();
const struct ChildrenNode* getChildren(int index);
static int addChildren(void* child, NodeType type);
static void delChildren(int index);
static const int N = 10;
private:
static ChildrenNode Children[N];
};
#endif //A_H
#include "A.h" A::A() { } A::~A() { } struct ChildrenNode A::Children[N] = {0}; const struct ChildrenNode* A::getChildren(int index) { if(index < 0 || index >= N) return 0; return &Children[index]; } int A::addChildren(void* child, NodeType type) { int i; if(child == 0) return false; if(type >= T_Count) return false; for(i = 0; i < N; i++) { if(Children[i].p == 0) break; else continue; } if(i >= N) return -1; Children[i].p = child; Children[i].type = type; return i; } void A::delChildren(int index) { if(index < N && index >= 0) { Children[index].p = 0; } }
#ifndef B_H #define B_H #include "A.h" class B : public A { public: B(); ~B(); void PrintSum(); private: int sum; }; #endif //B_H
#include "B.h" #includeB::B() { sum = addChildren((void*)this, T_B); } B::~B() { delChildren(sum); } void B::PrintSum() { printf("B: %d\n", sum); }
#ifndef C_H #define C_H #include "A.h" class C : public A { public: C(); ~C(); void PrintAllBsum(); }; #endif //C_H
#include "C.h" #include "B.h" C::C() { } C::~C() { } void C::PrintAllBsum() { int i; const struct ChildrenNode *node; for(i = 0; i < N; i++) { if((node = getChildren(i)) != 0) { if(node->p != 0 && node->type == T_B) ((B*)(node->p))->PrintSum(); } } }
#include "B.h" #include "C.h" #includeusing namespace std; int main(int argc, char** argv) { int i; B* b[A::N]; C c; for(i = 0; i < A::N; i++) { b[i] = new B(); sleep(1); c.PrintAllBsum(); } for(i = 0; i < A::N; i++) { if(b[i] != 0) delete b[i]; } return 0; }