我有许多使用相同通用函数/方法的类。目前我已经为每个类编写了这些方法,但这涉及不必要的重复。所以我想将这些方法移动到一个Utils类,可以被所有需要使用这些方法的类访问。我认为这可以通过Generic
或Template
来完成,但我没有一个我能理解的例子。
这就是我现在所做的(省略所有非必需品):
Genome.h:
ref class Genome
{
public:
List<wchar_t>^ stringToList(String^ inString); // convert string to List with chars
};
Genome.cpp:
List<wchar_t>^ Genome::stringToList (String^ inString)
{
List<wchar_t>^ tmpList = gcnew List<wchar_t>();
int i;
for (i = 0; i < inString->Length; i++)
tmpList->Add(inString[i]);
return tmpList;
}
,典型的方法调用如下所示:
cString->AddRange(stringToList(aLine)); // genome string is stored as one line
其中cString的类型为List<wchar_t>^
因此,如果我将stringToList
方法移动到Utils.h
和Utils.cpp
类,那么代码会是什么样的,以及如何调用此方法和其他Utils方法Genome.cpp和其他类?
谢谢,Jan
答案 0 :(得分:0)
我把我的实用程序函数放在一个我标记为抽象密封的类中。由于类是抽象密封的,因此无法创建它的实例,因此必须将所有成员声明为静态。结果相当于具有自由函数。
E.g。在标题中你将有
public ref class MyUtils abstract sealed
{
// ........................................................................
private:
static MyUtils ();
public:
static System::Double CalculateAverage ( cli::array<System::Double>^ arrayIn );
};
和.cpp
MyUtils::MyUtils ()
{
}
System::Double MyUtils::CalculateAverage ( cli::array<System::Double>^ arrayIn )
{
// the code doing the calculation...
}
在调用任何静态方法时调用此方法
e.g。
cli::array<System::Double>^ values = gcnew cli::array<System::Double>(5);
// ...
// put some data in the array
// ...
System::Double average = MyUtils::CalculateAverage ( values );
当然,您也可以使用泛型方法作为此类的成员。