程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> C++ 通過父類調用其他兄弟類實例

C++ 通過父類調用其他兄弟類實例

編輯:C++入門知識

簡述:

本文介紹一個類裡調用其兄弟類(繼承同一父類)的接口, 但是不直接傳遞兄弟類的實例給調用類實例.


場景:

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"
#include 

B::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"
#include 

using 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;
}

運行結果





  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved