C ++ / CLI类型转换运算符

时间:2012-05-09 04:50:34

标签: casting c++-cli operator-overloading

我有两个课程: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'

为什么第二种情况出错?

1 个答案:

答案 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;