C#-like properties in native C++?

后端 未结 11 1890
南笙
南笙 2020-11-29 04:46

In C# / .NET you can do something like this:

someThing.text = \"blah\";
String blah = someThing.text;

However, the above code does not actu

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 05:18

    WARNING: This is a tongue-in-cheek response and is terrible!!!

    Yes, it's sort of possible :)

    template
    class Property
    {
    private:
        T& _value;
    
    public:
        Property(T& value) : _value(value)
        {
        }   // eo ctor
    
        Property& operator = (const T& val)
        {
            _value = val;
            return *this;
        };  // eo operator =
    
        operator const T&() const
        {
            return _value;
        };  // eo operator ()
    };
    

    Then declare your class, declaring properties for your members:

    class Test
    {
    private:
        std::string _label;
        int         _width;
    
    public:
        Test() : Label(_label)
               , Width(_width)
        {
        };
    
        Property Label;
        Property         Width;
    };
    

    And call C# style!

    Test a;
    a.Label = "blah";
    a.Width = 5;
    
    std::string label = a.Label;
    int width = a.Width;
    

提交回复
热议问题