2010-07-13 56 views
0

我想为我的VBA项目创建一个COM类库,并且我似乎偶然发现的一个限制是在New()子例程上使用构造函数。创建新的COM类的Public Sub New()之后,用下面的评论在CCW上使用Sub New()的构造函数

' A creatable COM class must have a Public Sub New() 
' with no parameters, otherwise, the class will not be 
' registered in the COM registry and cannot be created 
' via CreateObject. 

很显然,虽然我想创造更多的子程序使用new关键字,允许不同的参数创建。但是,当我尝试执行此操作并在VBA中实现对象时,在尝试输入“期望结束语”参数时出现错误。如果有人有任何信息,将不胜感激。

谢谢。

回答

2

所有暴露给COM的类都必须有一个无参数的构造函数 - 句点。原因是当客户端实例化一个类时,调用最终会进入全局函数CoCreateInstance()(或者几乎相同的IClassFactory::CreateInstance())。 CoCreateInstance()(或IClassFactory::CreateInstance())没有办法将参数传递到类的构造函数中,以便类必须具有无量纲构造函数 - 该构造函数将用于在内部实例化类。

如果您需要比无参数的构造函数多 - 使用工厂类。伪代码:

// this should be made COM-exposed 
interface IYourClassInterface { 
}; 

// this should not be made COM-exposed 
class CYourClass { 
public: 
    CYourClass(parameters) {} 
}; 

class CYourClassFactory { 
public: 
    CYourClassFactory() {} //<- parameterless constructor 
    IYouClassInterface* CreateInstance(parameters here) 
    { 
     return new CYourClass(); 
    } 
}; 

这样你就有了一个带有无量纲构造函数的工厂类。您实例化工厂,然后调用其创建者方法来实例化您的类。

相关问题