如何使用C++/CX WinRT语法在.cpp文件中声明属性的实现?

8

我有一个像这样的类:

public ref class Test
{
public:
    property int MyProperty;
};

这很有效。我现在想将MyProperty的实现移动到CPP文件中。但是,当我这样做时,我得到编译器错误,指出该属性已经定义:

int Test::MyProperty::get() { return 0; }

这个应该用什么正确的语法呢?
2个回答

19
在头部更改声明为:
public ref class Test
{
public:
    property int MyProperty
    {
        int get();
        void set( int );
    }
private:
    int m_myProperty;
};

然后,在 CPP 代码文件中编写你的定义,如下所示:

int Test::MyProperty::get()
{
    return m_myProperty;
}
void Test::MyProperty::set( int i )
{
    m_myProperty = i;
}
你看到错误的原因是你声明了一个微不足道的属性,在这种情况下编译器会为你生成一个实现。然而,你尝试显式地提供实现,这就导致了错误。请参见:http://msdn.microsoft.com/en-us/library/windows/apps/hh755807(v=vs.110).aspx 大多数在线示例仅显示在类定义中直接实现的内容。

4
在类定义中,您需要将属性声明为具有用户声明的getset方法的属性;它不能是简写属性。
public ref class Test
{
public:

    property int MyProperty { int get(); void set(int); }
};

接着在cpp文件中,您可以定义get()set()方法:

int Test::MyProperty::get()
{
    return 42;
}

void Test::MyProperty::set(int)
{ 
    // set the value
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接