【问题标题】:C#-like properties in C++ [duplicate]C++ 中的类 C# 属性 [重复]
【发布时间】:2013-12-25 08:52:03
【问题描述】:

想着在C++中模拟C#的属性的方法,想到了以下解决方案:

#include <iostream>

class obj_with_property {
private:
    class mykey {};

public:
    class int_property {
    private:
        int m_v;
    public:
        int_property (int v, mykey) : m_v (v) {
        }

        int_property & operator = (int v) {
            m_v = v;
            return * this;
        }

        operator int () const {
            return m_v;
        }
    };

    int_property A;

    obj_with_property () : A (int_property (0, mykey ())) {
    }
};

int main(int argc, char **argv) {
    obj_with_property obj;
    std::cout << obj.A << std::endl;
    obj.A = 25;
    std::cout << obj.A << std::endl;
    return 0;
}

我想这种方法可以进一步改进,例如通过制作int_property 模板等。现在我无法想象我是第一个有这个想法的人。有人知道是否在任何地方讨论过类似的方法吗?

【问题讨论】:

  • 我在支持的默认值和分层属性中做了那种事情,并且是模板化的。我也曾经支持过 setter(这样property = x 会调用一个函数),但由于我的项目中没有使用它,所以我放弃了它。我认为您的方法是正确的。
  • 问题:“有人知道是否在任何地方讨论过类似的方法吗?”在这种情况下,我不必重新发明轮子。
  • 没有。我不想讨论如何在 C++ 中模拟属性。我的确切问题是,是否有任何 C++ 大师在众多 C++ 书籍或博客中的任何一本中讨论过这种特殊方法。
  • 它甚至在维基百科上,但不幸的是没有引用。 en.wikipedia.org/wiki/Property_%28programming%29#C.2B.2B

标签: c++ properties


【解决方案1】:

实际上,您可以使用模板轻松完成 - 这是一个基本实现: 现在我在你们的 cmets 中看到,你们不想要这样的答案,所以这是为了他人的利益。

我自己不会使用这种方法,因为在我创建的大多数库中,我不允许用户直接创建对象 - 所以如果没有进一步的包装,以下方法将无法工作。

template<class T>
class property
{
    T value_;
public:
    property(){}
    property(T v) : value_(v){}
    property(property<T> const & other) : value_(other.value_){}

    property<T> & operator=(property<T> const& other)
    {
        value_ = other.value_;
        return *this;
    }

    operator T(){return value_;}
};

class object_with_properties
{
public:
    object_with_properties(){}

    property<int> intP;
    property<double> doubleP;
    property<std::string> strP;
};

现在您可以通过以下方式在代码中使用它:

object_with_properties o;
o.intP = 1;
o.doubleP = 1.0;
o.strP = std::string("1");

现在这段代码有其局限性,因为 T 必须暴露一个默认构造函数,但它应该适用于允许用户直接创建对象的大多数情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2011-02-04
    • 2014-08-22
    • 1970-01-01
    • 2015-08-31
    相关资源
    最近更新 更多