C++11 有 C# 风格的属性吗? [英] Does C++11 have C#-style properties?
问题描述
在 C# 中,对于带有 getter 和 setter 的字段有一个很好的语法糖.此外,我喜欢允许我编写的自动实现的属性
In C#, there is a nice syntax sugar for fields with getter and setter. Moreover, I like the auto-implemented properties which allow me to write
public Foo foo { get; private set; }
在 C++ 中我必须写
In C++ I have to write
private:
Foo foo;
public:
Foo getFoo() { return foo; }
C++11 中是否有一些这样的概念允许我对此有一些语法糖?
Is there some such concept in the C++11 allowing me to have some syntax sugar on this?
推荐答案
在 C++ 中,您可以编写自己的功能.这是使用未命名类的属性的示例实现.维基百科文章
In C++ you can write your own features. Here is an example implementation of properties using unnamed classes. Wikipedia article
struct Foo
{
class {
int value;
public:
int & operator = (const int &i) { return value = i; }
operator int () const { return value; }
} alpha;
class {
float value;
public:
float & operator = (const float &f) { return value = f; }
operator float () const { return value; }
} bravo;
};
您可以编写自己的 getter &setter 就位,如果您想要持有者类成员访问权限,您可以扩展此示例代码.
You can write your own getters & setters in place and if you want holder class member access you can extend this example code.
这篇关于C++11 有 C# 风格的属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!