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
}