如何定义或ISO C ++实现C#房产吗? [英] How to Define or Implement C# Property in ISO C++?
问题描述
如何定义或ISO C实现的C#属性++
How to Define or Implement C# Property in ISO C++ ?
假设下面的C#代码:
int _id;
int ID
{
get { return _id; }
set { _id = value; }
}
我知道C#转换成get和set线的getXXX和setXXX方法编译时间。在C ++中,程序员通常定义这两个功能,手动,如:
I know C# convert the get and set lines to getXXX and setXXX methods in compile time. in C++ , programmers usually define these two function manually like :
int _id;
int getID() { return _id; }
void setID(int newID) { _id = newID; }
不过,我想有C#语法或为了有一个简单的喜欢它的东西可用性。
在C#中,我们可以用这样的属性:
but, I want to have the C# syntax or a stuff like it in order to have a simple usability. In C#, we can use properties like :
ID = 10; // calling set function
int CurrentID = ID; // calling get function
在C ++中,我们可以用我们喜欢的功能:
In C++, we can use our function like :
setID(10); // calling set function
int CurrentID = getID(); // calling get function
现在告诉我,我怎么能实现ISO C ++的C#属性。
Now tell me how can I implement the C# properties in ISO C++.
感谢。
推荐答案
由于亚历山大C.已经说明,这是非常,尴尬和不值得的,而是让你将如何做到这一点的例子
As Alexandre C. has already stated, it's very awkward and not really worth it, but to give an example of how you might do it.
template <typename TClass, typename TProperty>
class Property
{
private:
void (TClass::*m_fp_set)(TProperty value);
TProperty (TClass::*m_fp_get)();
TClass * m_class;
inline TProperty Get(void)
{
return (m_class->*m_fp_get)();
}
inline void Set(TProperty value)
{
(m_class->*m_fp_set)(value);
}
public:
Property()
{
m_class = NULL;
m_fp_set = NULL;
m_fp_set = NULL;
}
void Init(TClass* p_class, TProperty (TClass::*p_fp_get)(void), void (TClass::*p_fp_set)(TProperty))
{
m_class = p_class;
m_fp_set = p_fp_set;
m_fp_get = p_fp_get;
}
inline operator TProperty(void)
{
return this->Get();
}
inline TProperty operator=(TProperty value)
{
this->Set(value);
}
};
在你的类,你想使用它,您可以创建一个新的领域的财产,你必须调用初始化你的get / set方法传递给财产。 (在.ctor PREF)
In your class where you wish to use it, you create a new field for the property, and you must call Init to pass your get/set methods to the property. (pref in .ctor).
class MyClass {
private:
int _id;
int getID() { return _id; }
void setID(int newID) { _id = newID; }
public:
Property<MyClass, int> Id;
MyClass() {
Id.Init(this, &MyClass::getID, &MyClass::setID);
}
};
这篇关于如何定义或ISO C ++实现C#房产吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!