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

前端 未结 15 1073
伪装坚强ぢ
伪装坚强ぢ 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: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

提交回复
热议问题