What is the syntax to declare a C++/CX WinRT property with implementation in the .cpp file?

StackOverflow https://stackoverflow.com/questions/10485655

سؤال

I have a class like this:

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

This works. Now I want to move the implementation of MyProperty to the CPP file. I get compiler errors that the property is already defined when I do this:

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

What is the proper syntax for this?

هل كانت مفيدة؟

المحلول

In the header change the declaration to:

public ref class Test
{
public:
    property int MyProperty
    {
        int get();
        void set( int );
    }
private:
    int m_myProperty;
};

Then, in the cpp code file write your definitions like this:

int Test::MyProperty::get()
{
    return m_myProperty;
}
void Test::MyProperty::set( int i )
{
    m_myProperty = i;
}

The reason you are seeing errors is that you have declared a trivial property where the compiler generates an implementation for you. But, then you tried to provide an implementation explicitly as well. See: http://msdn.microsoft.com/en-us/library/windows/apps/hh755807(v=vs.110).aspx

Most of the examples online only show implementations directly in the class definition.

نصائح أخرى

In the class definition, you need to declare the property as a property with user-declared get and set methods; it cannot be a shorthand property:

public ref class Test
{
public:

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

Then in the cpp file you may define the get() and set() methods:

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

void Test::MyProperty::set(int)
{ 
    // set the value
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top