We can also use properties when we are programming in C++. In an "standard" way we can define a property class with templates but in Microsoft C++ is more easy. Microsoft C++ (since 6.0) provided us with a "property" attribute. Example:
class Human {
private:
int age;
public:
// This is the key line
__declspec( property( get = GetAge, put = SetAge)) int m_Age;
void SetAge(int a) {
if (a < 0)
age = 0;
else
age = a;
}
int GetAge() {
return age;
}
};
void main()
{
Human h;
h.m_Age = 10; // Set age data member to 10 calling SetAge
h.m_Age = -10; // Set age data member to 0 calling SetAge
cout << h.m_Age; // Get age data member calling GetAge
}
private:
int age;
public:
// This is the key line
__declspec( property( get = GetAge, put = SetAge)) int m_Age;
void SetAge(int a) {
if (a < 0)
age = 0;
else
age = a;
}
int GetAge() {
return age;
}
};
void main()
{
Human h;
h.m_Age = 10; // Set age data member to 10 calling SetAge
h.m_Age = -10; // Set age data member to 0 calling SetAge
cout << h.m_Age; // Get age data member calling GetAge
}
Comentarios
Publicar un comentario