【问题标题】:Assign CX public value struct contents of native C++ struct分配本机 C++ 结构的 CX 公共值结构内容
【发布时间】:2017-12-03 20:42:36
【问题描述】:

如果我有两个这样的结构:

struct A {
    float a;
    float b;
    float c;
    float d;
}

public value struct B {
    float a;
    float b;
    float c;
    float d;
}

从 A 转换为 B(反之亦然)的最佳方法是什么。我可以这样做吗:B struct_b = static_cast<B>(A{1,2,3,4})

【问题讨论】:

    标签: c++ struct c++-cx


    【解决方案1】:

    支持的方法是通过转换运算符:

    struct A;
    
    public value struct B {
        float a;
        float b;
        float c;
        float d;
    
    internal:
        operator A();
    };
    
    struct A {
        float a;
        float b;
        float c;
        float d;
    
        operator B()
        {
            return B{ a, b, c, d };
        }
    };
    
    B::operator A()
    {
        return A{ a, b, c, d };
    }
    

    请注意,Intellisense 可能会抱怨 operator A() 带有红色波浪线和有关“公共非数据成员”的工具提示,但您可以忽略它并且代码将编译。 internal 关键字的意思是“public 在 C++ 中,但不作为 WinMD 中元数据的一部分公开。”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      相关资源
      最近更新 更多