问题描述
我希望部分初始化结构数组,例如C ++ POD类型。 String ^通常是char *,但是托管C ++不允许这样做。
#include "stdafx.h"
using namespace System;
ref struct Field
{
String^ name;
int fences;
int length;
};
int main(array<System::String ^> ^args)
{
array<Field^>^ farm =
{
{ "eenie",10 },{ "meenie",20 },{ "miny",4 }
};
for each (Field^ field in farm)
{
field->length = field->fences * 22;
}
return 0;
}
这导致
1>arrayinit.cpp(18): error C2440: 'initializing' : cannot convert from 'const char [6]' to 'Field ^'
1> Reason: cannot convert from 'const char *' to 'Field ^'
1> No user-defined-conversion operator available,or
1> Cannot convert an unmanaged type to a managed type
所以我尝试了
#include "stdafx.h"
using namespace System;
ref struct Field
{
String^ name;
int fences;
int length;
};
int main(array<System::String ^> ^args)
{
array<Field^>^ farm =
{
{ String("eenie"),{ String("meenie"),{ String("miny"),4 }
};
for each (Field^ field in farm)
{
field->length = field->fences * 22;
}
return 0;
}
现在我得到
1>arrayinit.cpp(18): error C2440: 'initializing' : cannot convert from 'System::String' to 'Field ^'
1> No user-defined-conversion operator available,or
1> No user-defined-conversion operator available that can perform this conversion,or the operator cannot be called
1>arrayinit.cpp(18): error C2078: too many initializers
我看过的几乎每个示例都仅说明了如何初始化字符串或整数数组。我还没有找到初始化包含字符串的结构数组的方法。
是否有一种简单的方法?还是必须创建一个特殊的构造函数并gcnew每个元素?
解决方法
我发现我可以使用特殊的构造函数gcnew每个元素。有没有一种类似于POD初始化的简单方法?
constructor(props){
super(props);
this.state = {
loading: true
};
//....
this.tempoRealeDestro = [];
this.tempoRealeSinistro = [];
}
dataReceived(){
this.dimensioneArrayRaggiunta = this.props.dimensioneArrayRaggiunta;
if(this.checkContatore == false){
this.contatoreDestro = this.props.contatoreTimestampDestro;
this.contatoreSinistro = this.props.contatoreTimestampSinistro;
this.checkContatore = true;
}
this.stopClick();
}
或者,如果将Field更改为值而不是引用,
#include "stdafx.h"
using namespace System;
ref struct Field
{
String^ name;
int fences;
int length;
Field(String^ x,int in_fences)
{
name = x;
fences = in_fences;
}
};
int main(array<System::String ^> ^args)
{
array<Field^>^ farm =
{
gcnew Field("eenie",10 ),gcnew Field("meenie",20 ),gcnew Field("miny",4 )
};
for each (Field^ field in farm)
{
field->length = field->fences * 22;
}
return 0;
}
这比对每个字段进行更新要好一些。