2012-05-09 60 views
1

我有兩個類:testClasscastClassC++/CLI類型轉換操作符

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

也許是因爲現在c已經是引用,所以它將'c%'解釋爲'c %%'(雙引用)。如果是這樣,我不知道你將如何去參考。 – karmasponge

+0

您正嘗試將一個指針轉換爲一個對象,但不允許。你可以直接調用操作符:'testClass j = castClass :: operator testClass(c);' –

回答

2

由於castClass是引用類,所以引用該類型對象的常規方法是使用^。試試這個,它應該適合你。

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; 
相關問題