【问题标题】:C++/CLI type-cast operatorC++/CLI 类型转换运算符
【发布时间】:2012-05-09 04:50:33
【问题描述】:

我有两个班级: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'

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

【问题讨论】:

  • 也许是因为现在 c 已经是引用,所以它将 'c%' 解释为 'c%%' (双重引用)。如果是,我不确定您将如何取消引用。
  • 您正在尝试将指针强制转换为对象,这是不允许的。您可以直接调用运算符:testClass j = castClass::operator testClass(c);

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


【解决方案1】:

因为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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多