C++实现属性源代码(借鉴,模仿)
//property.h#pragma once#include <assert.h>int const READ_ONLY = 1;int const WRITE_ONLY = 2;int const READ_WRITE = 4;template<class CContainer, class CPropType, int nAccessType>class CProperty{public:CProperty(){m_pobjContain = NULL;m_pfunSet = NULL;m_pfunGet = NULL;}~CProperty(){}public:void SetContainer(CContainer* pContain){m_pobjContain = pContain;}void SetSetFunction(void (CContainer::*pSet)(CPropType val) ){if ( (WRITE_ONLY == nAccessType) || (READ_WRITE == nAccessType) ){m_pfunSet = pSet;}else{m_pfunSet = NULL;}}void SetGetFunction(CPropType (CContainer::*pGet)() ){if ( (READ_ONLY == nAccessType) || (READ_WRITE == nAccessType) ){m_pfunGet = pGet;}else{m_pfunGet = NULL;}}CPropType operator = (const CPropType& val){assert(NULL != m_pobjContain);assert(NULL != m_pfunSet);(m_pobjContain->*m_pfunSet)(val);return val;}operator CPropType(){assert(NULL != m_pobjContain);assert(NULL != m_pfunGet);return (m_pobjContain->*m_pfunGet)();}private:CContainer*m_pobjContain;void (CContainer::*m_pfunSet)(CPropType val);CPropType (CContainer::*m_pfunGet)();};//main.cpp// UseProp.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include "Property.h"#include <iostream>using namespace std;class CPropTest{public:CPropTest(int nVal = 0){m_nData = nVal;m_nVal.SetContainer(this);m_nVal.SetSetFunction(&CPropTest::SetData);m_nVal.SetGetFunction(&CPropTest::GetData);}~CPropTest(){}public:CProperty<CPropTest, int, READ_WRITE> m_nVal;int GetData(){return m_nData;}void SetData(int nVal){m_nData = nVal;}private:intm_nData;};int main(){CPropTest obj;obj.m_nVal = 10;int nVal = obj.m_nVal;cout << obj.m_nVal << endl;return 0;}
页:
[1]