我有一个像这样的类:
public ref class Test
{
public:
property int MyProperty;
};
这很有效。我现在想将MyProperty的实现移动到CPP文件中。但是,当我这样做时,我得到编译器错误,指出该属性已经定义:
int Test::MyProperty::get() { return 0; }
这个应该用什么正确的语法呢?
我有一个像这样的类:
public ref class Test
{
public:
property int MyProperty;
};
这很有效。我现在想将MyProperty的实现移动到CPP文件中。但是,当我这样做时,我得到编译器错误,指出该属性已经定义:
int Test::MyProperty::get() { return 0; }
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
大多数在线示例仅显示在类定义中直接实现的内容。get
和set
方法的属性;它不能是简写属性。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
}