1

我有两个班级:testClasscastClass

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'

为什么第二种情况是错误的?

4

1 回答 1

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;
于 2012-05-09T18:42:08.627 回答