我有两个课程:testClass
和castClass
:
class testClass
{
public:
int field1;
int field2;
testClass(int f1, int f2) : field1(f1), field2(f2) {}
};
ref class castClass
{
int i;
int j;
public:
castClass(int i, int j) : i(i), j(j) {}
explicit static operator testClass (castClass% c)
{
return testClass(c.i, c.j);
}
};
当我尝试:
castClass cc(1, 2);
testClass i = (testClass)cc;
编译得很好。
但当我尝试施放时:
castClass% c = castClass(1, 2);
testClass j = (testClass)c;
编译器抛出错误:
Error 1 error C2440: 'type cast' : cannot convert from
'castClass' to 'testClass'
为什么第二种情况出错?
答案 0 :(得分:2)
因为castClass
是一个ref类,所以引用该类型对象的常规方法是使用^
。试试这个,它应该适合你。
ref class castClass
{
int i;
int j;
public:
castClass(int i, int j) : i(i), j(j) {}
explicit static operator testClass (castClass^ c)
{
return testClass(c->i, c->j);
}
};
castClass^ cc = gcnew castClass(1, 2);
testClass i = (testClass)cc;
castClass^% c = gcnew castClass(1, 2);
testClass j = (testClass)c;