屬性,是面向?qū)ο蟪绦蛟O(shè)計(jì)中不可缺少的元素,廣義的屬性是用來(lái)描述一個(gè)對(duì)象所處于的狀態(tài)。
而我們這篇文章所說(shuō)的屬性是狹義的,指能用“=”操作符對(duì)類的一個(gè)數(shù)據(jù)進(jìn)行g(shù)et或set操作,而且能控制get和set的權(quán)限。
??????? 先看一下代碼:
#include <IOSTREAM>
#include <map>
#include <string>
#include <CONIO.H>
using namespace std;
class propertytest{
int m_xvalue;
int m_yvalues[100];
map<string,string> m_zvalues;
public:
__declspec(property(get=GetX, put=PutX))
int x;
__declspec(property(get=GetY, put=PutY))
int y[];
__declspec(property(get=GetZ, put=PutZ))
int z[];
int GetX()
{
return m_xvalue;
?};
void PutX(int x)
?{
m_xvalue = x;
};
int GetY(int n)
{
return m_yvalues[n];
};
void PutY(int n,int y)
{
m_yvalues[n] = y;
};
string GetZ(string key)
{
return m_zvalues[key];
};
void PutZ(string key,string z)
{
m_zvalues[key] = z;
};
};
int main(int argc, char* argv[]){
propertytest test;
test.x = 3;
test.y[3] = 4;
test.z["aaa"] = "aaa";
std::cout << test.x <<std::endl;
std::cout << test.y[3] <<std::endl;
std::cout << test.z["aaa"] <<std::endl; getch();
return 0;
}
__declspec(property(get=[get方法名], put=[put方法名])) [類型] [屬性名];
??????? __declspec(property)實(shí)際上就是做了一個(gè)映射,把你的方法映射成屬性,以供訪問(wèn)。
get和put就是屬性訪問(wèn)的權(quán)限,一個(gè)是讀的權(quán)限,一個(gè)是寫的權(quán)限。你可以根據(jù)需要來(lái)決定get和put兩種權(quán)限的取舍。