为什么属性不能在ref class中密封

时间:2013-11-20 22:50:44

标签: c++ pointers direct3d c++-cx

以下代码是非法的(Visual Studio 2012 Windows Phone(创建Windows Phone direct3d应用程序))

a non-value type cannot have any public data members 'posX'

标题

ref class Placement sealed
{
public:
    Placement(
        float rotX, 
        float rotY, 
        float rotZ, 
        float posX, 
        float posY, 
        float posZ
    );
    float rotX, rotY, rotZ, posX, posY, posZ;
};

.cpp的

Placement::Placement(
        float rotX, 
        float rotY, 
        float rotZ, 
        float posX, 
        float posY, 
        float posZ
    )
    :   posX( posX ),
        posY( posY ),
        posZ( posZ )
{
    this->rotX = static_cast<float>(rotX);
    this->rotY = static_cast<float>(rotY);
    this->rotZ = static_cast<float>(rotZ);
}

为什么以及如何设置属性?我习惯普通的C ++而不是C ++ CX(我认为它被称为正确吗?)...我是否必须创建为属性提供服务的方法?

*这个问题源于我最初尝试创建一个普通的类并创建一个指向它的指针,只是抱怨我不能使用*而不是我必须使用^这意味着我必须创建一个ref类代替... 我真的不明白为什么?*

是否与WinRT或更具体的ARM处理器有关?

2 个答案:

答案 0 :(得分:6)

是COM中的限制,是WinRT和C ++ / CX语言扩展的基础。 COM仅允许接口声明中的纯虚方法。属性很好,它被模拟为getter和setter方法。不是一个领域。

这种限制不是人为的,它强烈地删除了实现细节。当您需要支持任意语言并让它们相互通信或与API通信时非常重要。字段具有非常讨厌的实现细节,其位置非常依赖于实现。对齐和结构打包规则对于确定位置非常重要,并且无法保证在语言运行时之间保持兼容。

使用属性是一种简单的解决方法。

答案 1 :(得分:4)

这是特定于WinRT和C ++ / CX扩展的特定内容。 C ++ / CX不允许ref类包含公共字段。您需要使用公开properties替换您的公共字段。

 ref class Placement sealed
{
public:
    Placement(
        float rotX, 
        float rotY, 
        float rotZ, 
        float posX, 
        float posY, 
        float posZ
    );
    property float rotX;
    property float rotY;
    property float rotZ;
    property float posX;
    property float posY;
    property float posZ;
};

属性具有由编译器自动为它们生成的getter和setter函数。

相关问题