【发布时间】:2012-05-09 04:50:33
【问题描述】:
我有两个班级: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'
为什么第二种情况是错误的?
【问题讨论】:
-
也许是因为现在 c 已经是引用,所以它将 'c%' 解释为 'c%%' (双重引用)。如果是,我不确定您将如何取消引用。
-
您正在尝试将指针强制转换为对象,这是不允许的。您可以直接调用运算符:
testClass j = castClass::operator testClass(c);
标签: casting c++-cli operator-overloading