关于C++实现属性的方法

实现属性的模板类

在Property.h文件中实现如下代码

#include 
#ifndef _PROPERTY_H_
#define _PROPERTY_H_

#define READ_ONLY 1
#define WRITE_ONLY 2
#define READ_WRITE 3

template <typename Container, typename ValueType, int nPropType>
class Property {
public:
	Property()
	{
		m_cObject = 0;
		Set = 0;
		Get = 0;
	}
	//-- This to set a pointer to the class that contain the
	//   property --
	void setContainer(Container* cObject)
	{
		m_cObject = cObject;
	}
	//-- Set the set member function that will change the value --
	void setter(void (Container::*pSet)(ValueType value))
	{
		if ((nPropType == WRITE_ONLY) || (nPropType == READ_WRITE))
			Set = pSet;
		else
			Set = 0;
	}

	//-- Set the get member function that will retrieve the value --
	void getter(ValueType(Container::*pGet)())
	{
		if ((nPropType == READ_ONLY) || (nPropType == READ_WRITE))
			Get = pGet;
		else
			Get = 0;
	}
	//-- Overload the '=' sign to set the value using the set
	//   member --
	ValueType operator =(const ValueType& value)
	{
		assert(m_cObject != 0);
		assert(Set != 0);
		(m_cObject->*Set)(value);
		return value;
	}

	//-- To make possible to cast the property class to the
	//   internal type --
	operator ValueType()
	{
		assert(m_cObject != 0);
		assert(Get != 0);
		return (m_cObject->*Get)();
	}
private:
	Container* m_cObject;
	//-- Pointer to the module that
    //   contains the property --
	void (Container::*Set)(ValueType value);
	//-- Pointer to set member function --
	ValueType(Container::*Get)();
	//-- Pointer to get member function --
};

#endif /* SRC_PROPERTY_H_ */

使用方法

PathPlanning.h文件代码实现如下:

#ifndef _PATHPLANNING_H_
#define _PATHPLANNING_H_
#include "Property.h"
class PathPlanning
{
private:
int _steering_wheel_target_angle;

public:
PathPlanning();

int getSteeringWheelTargetAngle();
void setSteeringWheelTargetAngle(int value);
Property<PathPlanning,int,READ_WRITE> SteeringWheelTargetAngle;
};
#endif /* _PATHPLANNING_H_ */

PathPlanning.c文件代码实现如下:

#include "Property.h"
#include "PathPlanning.h"

PathPlanning::PathPlanning()
{
	SteeringWheelTargetAngle.setContainer(this);
	SteeringWheelTargetAngle.setter(&PathPlanning::setSteeringWheelTargetAngle);
	SteeringWheelTargetAngle.getter(&PathPlanning::getSteeringWheelTargetAngle);
}

int PathPlanning::getSteeringWheelTargetAngle()
{
	return _steering_wheel_target_angle;
}

void PathPlanning::setSteeringWheelTargetAngle(int value)
{
	_steering_wheel_target_angle = value;
}

最终实现

main.cpp文件调用

#include "PathPlanning.h"
int main()
{
	PathPlanning m_PathPlanning;
    m_PathPlanning.SteeringWheelTargetAngle = 30;
    int d = m_PathPlanning.SteeringWheelTargetAngle;
	return 0;
}

参考链接

你可能感兴趣的:(C++)