六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 163|回复: 0

C++实现属性源代码(借鉴,模仿)

[复制链接]

升级  81.33%

142

主题

142

主题

142

主题

举人

Rank: 3Rank: 3

积分
444
 楼主| 发表于 2013-2-5 02:17:19 | 显示全部楼层 |阅读模式
//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;}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表