Does C++11 have C#-style properties?

前端 未结 15 1031
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 03:16

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 fo         


        
相关标签:
15条回答
  • 2020-11-28 03:56

    You can emulate getter and setter to some extent by having a member of dedicated type and overriding operator(type) and operator= for it. Whether it's a good idea is another question and I'm going to +1 Kerrek SB's answer to express my opinion thereon :)

    0 讨论(0)
  • 2020-11-28 03:58

    I collected the ideas from multiple C++ sources and put it into a nice, still quite simple example for getters/setters in C++:

    class Canvas { public:
        void resize() {
            cout << "resize to " << width << " " << height << endl;
        }
    
        Canvas(int w, int h) : width(*this), height(*this) {
            cout << "new canvas " << w << " " << h << endl;
            width.value = w;
            height.value = h;
        }
    
        class Width { public:
            Canvas& canvas;
            int value;
            Width(Canvas& canvas): canvas(canvas) {}
            int & operator = (const int &i) {
                value = i;
                canvas.resize();
                return value;
            }
            operator int () const {
                return value;
            }
        } width;
    
        class Height { public:
            Canvas& canvas;
            int value;
            Height(Canvas& canvas): canvas(canvas) {}
            int & operator = (const int &i) {
                value = i;
                canvas.resize();
                return value;
            }
            operator int () const {
                return value;
            }
        } height;
    };
    
    int main() {
        Canvas canvas(256, 256);
        canvas.width = 128;
        canvas.height = 64;
    }
    

    Output:

    new canvas 256 256
    resize to 128 256
    resize to 128 64
    

    You can test it online here: http://codepad.org/zosxqjTX

    0 讨论(0)
  • 2020-11-28 03:59

    Based on https://stackoverflow.com/a/23109533/404734 here is a version with a public getter and a private setter:

    struct Foo
    {
        class
        {
                int value;
                int& operator= (const int& i) { return value = i; }
                friend struct Foo;
            public:
                operator int() const { return value; }
        } alpha;
    };
    
    0 讨论(0)
提交回复
热议问题