[上下文:Java 新手,最多 4 个月;C++ 的老手。]
我正在开发一个库,该库在许多地方都需要一个固定大小的数组(“固定字符串”)。我正在尝试对这个特定问题使用依赖注入(qv),所以我想要以下形式的东西:
class Foo
{
private Bar injectedBar;
private char[] injectedFixedString;
Foo(Bar injectedBar, /* what can go here? */ char[5] injectedFixedString);
{ /* initializing code goes here /* }
}
需要简单——这将进入一个自动生成的通信协议。我对派生它的协议和数据库的控制为零;我将在最终代码中包含数百个(如果不是数千个)这些实例。因此,鉴于所有这些:
是我唯一的 C++ 替代方案:
char injectedFixedString[5];
创建一个自定义类?就像是:
class FixedBarString {
/* could also set this in the constructor, but this complicates code generation a tad */
public static integer STRING_SIZE = 5; /* string size */
char[] fixedString = new char[STRING_SIZE];
FixedBarString(char[] string) throws RuntimeException {
/* check the string here; throw an exception if it's the wrong size.
I don't like constructors that throw however. */
}
public void setString(char[] string) throws RuntimeException {
/* check the string here */
}
public char[] getString() {
/* this isn't actually safe, aka immutable, without returning clone */
}
public char[] createBlankString() {
return new char[STRING_SIZE];
}
}
谢谢。(如果代码太多,我深表歉意)。