COM聚合的简单模拟

COM中的聚合原理看起来比较简单,但是由于其要实现两个IUnkNown,所以实现起来比包容复杂,下面我做了个简单的模拟程序,看起来就比较容易理解,代码如下:

#include <iostream.h>

class IUnkNown
{
public:



virtual void funcM() = 0;
virtual void funcN() = 0;
virtual void funcP() = 0;
};

class INondelegation
{
public:
virtual void nonfuncM() = 0;
virtual void nonfuncN() = 0;
virtual void nonfuncP() = 0;

};

class A : public IUnkNown
{
public:

virtual void funcM();
virtual void funcN();
virtual void funcP();

};
#if 1
void A::funcM()
{
cout<<"class A funcM IUnkNown"<<endl;
}

void A::funcN()
{
cout<<"class A funcN IUnkNown"<<endl;
}

void A::funcP()
{
cout<<"class A funcP IUnkNown"<<endl;
}
#endif


class B : public A,
public INondelegation
{
public:
B::B();

virtual void funcM()
{
cout<<"class B funcM - INondelegation"<<endl;
}

virtual void funcN()
{
cout<<"class B funcN - INondelegation"<<endl;
}

virtual void funcP()
{
cout<<"class B funcP - INondelegation"<<endl;
}

virtual void nonfuncM();
virtual void nonfuncN();
virtual void nonfuncP();

};

B::B()
{

}


void B::nonfuncM()
{
cout<<"class B funcM INondelegation,no delegation"<<endl;
}


void B::nonfuncN()
{
cout<<"class B funcN INondelegation,no delegation"<<endl;
}

void B::nonfuncP()
{
cout<<"class B funcP INondelegation,no delegation"<<endl;
}

void trans(B& bt,void** pvv)
{
#if 1
*pvv = static_cast<A*>(&bt);
#else
*pvv = static_cast<INondelegation*>(&bt);
#endif
reinterpret_cast<IUnkNown*>(*pvv)->funcM();

}


void main()
{
#if 1
//A a;
B b;
B* pp = &b;
IUnkNown* pa = NULL;
trans(b,(void**)&pa);


//reinterpret_cast<IUnkNown*>(pa)->funcM();

//pa->funcM();
#else

/*
B b;
INondelegation* pfb = &b;
IUnkNown* pb = (IUnkNown*)&b;
pb->funcM();
//pfb->nonfuncM();

*/

#endif

}

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...