property属性

在C++中也可以使用像C#中的属性。在某些特定的环境我们可以使用这一方法,虽然在效率上会比直接访问要来得慢。但是这点效率基本可以忽略的。。代码大致如下:

#include <iostream>
using namespace std;

class test
{
public:
int get( void )
{
return m_nLevel;
}

void set( int value )
{
m_nLevel = value;
}

__declspec( property( get = get, put = set ) ) int level;

private:
int m_nLevel;
};

int main()
{
test ts;
ts.level = 100;
cout << ts.level << endl;
system( "pause" );
return 0;
}

我们使用 __declspec( property( get = ???, put = ???) ) ???;来定义某个成员的get和set方法。

我们在调用这个成员的时候,便会自动调用set或get方法,然后将我们的私有成员传递给我们公用的属性成员。

还有一种定义属性成员:

//定义属性:
ref class X
{
property int a;
property float b {
float get() {

}
void set(float v) {

}
}
property String^ c[int] {
String^ get(int i) {

}
void set(int i, String^ v) {

}
}
};

//访问属性:
X x;
x.a=21;
float f=x.b;
x.c[3]=”ok”;

原文地址:https://www.cnblogs.com/ouyangping/p/7966691.html