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

2

8

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?

Echt answered 7/5, 2012 at 16:28 Comment(0)
H
19

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.

Hukill answered 7/5, 2012 at 16:36 Comment(0)
L
4

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
}
Landry answered 7/5, 2012 at 16:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.